select scope_identity();
ex)
string comString = "insert MyTable (custName) values ('John'); select scope_identity()";
SqlCommand com = new SqlCommand(comString);
int latestCustromerId = (int)com.ExecuteScalar();
SqlParameter spIdx = new SqlParameter("@idx", SqlDbType.Int);
spIdx.Direction = ParameterDirection.Output;
SqlParameter spFilename = new SqlParameter("@FileName", SqlDbType.NVarChar, 250);
spFilename.Value = fileName;
SqlParameter spImage = new SqlParameter("@Image", SqlDbType.Image);
spImage.Value = image;
scmd.Parameters.Add(spIdx);
scmd.Parameters.Add(spFilename);
scmd.Parameters.Add(spImage);
sc.Open();
scmd.ExecuteNonQuery();
sc.Close();
int newIdx = (int)spIdx.Value;
static public int AddProductCategory(string newName, string connString)
{
Int32 newProdID = 0;
string sql =
"INSERT INTO Production.ProductCategory (Name) VALUES (@Name); "
+ "SELECT CAST(scope_identity() AS int)";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("@Name", SqlDbType.VarChar);
cmd.Parameters["@name"].Value = newName;
try
{
conn.Open();
newProdID = (Int32)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
return (int)newProdID;
}