public static int ExecuteIdentityInsert
(string connection,
string commandtext,
string tablename,
Dictionary<string, string> parameters)
{
SqlConnection con = new SqlConnection(connection);
string getIdentityCommandText =
(";SELECT ID FROM " + tablename + " WHERE (ID = SCOPE_IDENTITY())");
Object result;
using (con)
{
con.Open();
// Add query to retrieve inserted command id
SqlCommand com = new SqlCommand(commandtext+getIdentityCommandText, con);
if (parameters != null)
{
foreach (KeyValuePair<string, string> pair in parameters)
{
com.Parameters.AddWithValue(pair.Key, pair.Value);
}
}
try
{
result = com.ExecuteScalar();
}
catch (Exception ex)
{
throw;
}
}
return Convert.ToInt32(result);
}
Monday, July 13, 2009
Get Identity after SQL Insert Command
The following code will allow you to execute an insert command and retrieve the identity of the inserted record in a single method. The use of (ID = SCOPE_IDENTITY()) will prevent any triggers from providing incorrect ID results that can be obtained when using @@Identity.
Subscribe to:
Post Comments (Atom)

No comments:
Post a Comment