同题。
比如create table tst
(
tID int primary key identity(1,1),
tstr varchar(40) not null
)insert into tst(tstr) values('测试')有这样一个tst表,tID字段为自增的,对于刚插入的记录,如何在asp.net中直接获得刚插入记录的ID值。。纠结
(
我有一种恶心的办法,也不太安全,勉强可以实现,就是select top 1 tID from tst where tstr='刚刚插入的记录' order by tID desc)
但是这种方法在很多人连接数据库操作的时候很有可能返回的ID是错误的,请介绍其他可行实用的方法~
谢谢!!
比如create table tst
(
tID int primary key identity(1,1),
tstr varchar(40) not null
)insert into tst(tstr) values('测试')有这样一个tst表,tID字段为自增的,对于刚插入的记录,如何在asp.net中直接获得刚插入记录的ID值。。纠结
(
我有一种恶心的办法,也不太安全,勉强可以实现,就是select top 1 tID from tst where tstr='刚刚插入的记录' order by tID desc)
但是这种方法在很多人连接数据库操作的时候很有可能返回的ID是错误的,请介绍其他可行实用的方法~
谢谢!!
cmd.ExecuteNonQuery();
cmd.CommandText = "SELECT @@IDENTITY";
int newId = (int)cmd.ExecuteScalar();
通过存储过程参数获取output 值
SCOPE_IDENTITY 返回为当前会话和当前作用域中的任何表最后生成的标识值。
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;
}