开发者

sqldatasource insert return identity value

开发者 https://www.devze.com 2023-01-18 05:16 出处:网络
Im usingSqlDataSource sds = new SqlDataSource(); in code behind and inserting using sds.Insert(); Please 开发者_如何学Pythontell me how to get inserted record primary key value?

Im using SqlDataSource sds = new SqlDataSource(); in code behind and inserting using sds.Insert(); Please 开发者_如何学Pythontell me how to get inserted record primary key value? Please note im not using stored procedure.


Last_Insert_ID();

Gives you the last primary key id, you can simply append this on the end of your current insert and the key value will be returned from your insert.

here is a C# example:

tring sqlIns = "INSERT INTO table (name, information, other) VALUES (@name, @information, @other)";
db.Open();
try
{
 SqlCommand cmdIns = new SqlCommand(sqlIns, db.Connection);
 cmdIns.Parameters.Add("@name", info);
 cmdIns.Parameters.Add("@information", info1);
 cmdIns.Parameters.Add("@other", info2);
 cmdIns.ExecuteNonQuery();

 cmdIns.Parameters.Clear();
 cmdIns.CommandText = "SELECT @@IDENTITY";


 // Get the last inserted id.

 int insertID = Convert.ToInt32( cmdIns.ExecuteScalar() );


 cmdIns.Dispose();
 cmdIns = null;
}
catch(Exception ex)
{
throw new Exception(ex.ToString(), ex);
}
finally
{
db.Close();
}

I found this at MSDN:

http://social.msdn.microsoft.com/forums/en-US/csharpgeneral/thread/91bd10ce-c83b-4766-920b-2137ddc29908


I know this is a rather old post but in case someone lands here contemporaneously ...

Regarding Michael Eakins answer (see above), it is safer to use SCOPE_IDENTITY() rather than @@IDENTITY.

Per MSDN SCOPE_IDENTITY

"... SCOPE_IDENTITY returns values inserted only within the current scope; @@IDENTITY is not limited to a specific scope."

0

精彩评论

暂无评论...
验证码 换一张
取 消