ASU Web Community

ASP.NET C# & SQL Insert Statement Duplicate Records Issue

Tuesday, April 14th, 2009 - 4:13 pm
  • jwchapma

Hello,

I am trying to insert a new record and obtain the indentity of the newly created record. The code below works, however it generates two records instead of one. Any ideas why?

sqlConn.Open();
sqlCmd = new SqlCommand("INSERT INTO [tbl_vendor] ([vendor_name]) VALUES (@vendor_name) SELECT SCOPE_IDENTITY()", sqlConn);
sqlCmd.Parameters.Add(new SqlParameter("@vendor_name", SqlDbType.NVarChar, 100)).Value = companyname;
sqlCmd.ExecuteNonQuery();
int iCompany = Convert.ToInt32(sqlCmd.ExecuteScalar());
companyid = iCompany.ToString();
sqlConn.Close();

Thanks,

John Chapman

Tuesday, April 28th, 2009 - 7:23 am
  • cscholtz
  • cscholtz's picture

Hi first create and execute the insert statement. Next clear the parameters. Finally, call the select @@IDENTITY.

sqlCmd = new SqlCommand("INSERT INTO [tbl_vendor] ([vendor_name]) VALUES (@vendor_name) SELECT SCOPE_IDENTITY()", sqlConn);
sqlCmd.Parameters.Add(new SqlParameter("@vendor_name", SqlDbType.NVarChar, 100)).Value = companyname;
sqlConn.Open();
sqlCmd.ExecuteNonQuery();

sqlCmd.Parameters.Clear();

sqlCmd.CommandText = "SELECT @@IDENTITY";
int iCompany = Convert.ToInt32(sqlCmd.ExecuteScalar());
sqlConn.Close();

cheers,

Cameron