将 id 标识值存储在变量中
Storing the id identity value in a variable
我正在使用 ASP.NET、C# 和 SQL Server 2012。
我有一个按钮可以插入到名为 images
的 table 中的新行中,我正在使用 identity
为 image_id
.
我还有其他 table 外键 image_id
。
我想要的是将新生成的image_id
的值存储在一个变量中,稍后在其他函数中使用它。
我无法使用最后一行的值,因为我会将 table 与其他按钮一起使用,如果它们同时单击,它们可能会获得其他按钮的数据。
有没有办法将新插入行的确切ID保存在变量中?
构建一个class并将其存储在class中。
public class yourClass
{
private int image_id;
public int Image_id
{
get
{
return image_id;
}
set
{
image_id= value;
}
}
}
在生成 image_id 的代码中,将 yourClass.Image_id 设置为新值。
当您插入一条新记录时,作为 同一批次 的一部分,还调用 scope_identity()
和 return 结果返回给您的程序.它可能看起来像这样:
int newIDValue;
using (var cn = new SqlConnection("connection string here"))
using (var cmd = new SqlCommand("INSERT INTO [table] (...) VALUES (...); SELECT scope_idenity;"))
{
cn.Open();
newIDValue = (int)cmd.ExecuteScalar();
}
请注意 SQL 命令实际上是同一个字符串中的两个语句。
我正在使用 ASP.NET、C# 和 SQL Server 2012。
我有一个按钮可以插入到名为 images
的 table 中的新行中,我正在使用 identity
为 image_id
.
我还有其他 table 外键 image_id
。
我想要的是将新生成的image_id
的值存储在一个变量中,稍后在其他函数中使用它。
我无法使用最后一行的值,因为我会将 table 与其他按钮一起使用,如果它们同时单击,它们可能会获得其他按钮的数据。
有没有办法将新插入行的确切ID保存在变量中?
构建一个class并将其存储在class中。
public class yourClass
{
private int image_id;
public int Image_id
{
get
{
return image_id;
}
set
{
image_id= value;
}
}
}
在生成 image_id 的代码中,将 yourClass.Image_id 设置为新值。
当您插入一条新记录时,作为 同一批次 的一部分,还调用 scope_identity()
和 return 结果返回给您的程序.它可能看起来像这样:
int newIDValue;
using (var cn = new SqlConnection("connection string here"))
using (var cmd = new SqlCommand("INSERT INTO [table] (...) VALUES (...); SELECT scope_idenity;"))
{
cn.Open();
newIDValue = (int)cmd.ExecuteScalar();
}
请注意 SQL 命令实际上是同一个字符串中的两个语句。