如何在插入记录后从SQL server获取Identity值

本文关键字:server SQL 获取 Identity 插入 记录 | 更新日期: 2023-09-27 18:25:37

我在数据库中添加了一条具有identity值的记录。我想在插入后获得标识值。我不想通过存储过程来做到这一点。

这是我的代码:

SQLString = " INSERT INTO myTable ";
SQLString += " (Cal1, Cal2, Cal3, Cal4) ";
SQLString += " VALUES(N'{0}',N'{1}',N'{2}',N'{3}') ";
SQLString = string.Format(SQLString, Val1, Val2, Val3, Val4);
SQLString += " Declare @_IdentityCode INT SET @_IdentityCode = @@IDENTITY RETURN @_IdentityCode";
int result;
public int DoCommand2(string sql)
{
        con = new SqlConnection();
        cmd = new SqlCommand();
        da = new SqlDataAdapter();
        cmd.Connection = con;
        da.SelectCommand = cmd;
        string cs = GlobalConstants.SqlConnectionString;
        con.ConnectionString = cs;
        cmd.CommandText = sql;
        int i = cmd.ExecuteNonQuery();
        return i;
}

但我得到了这个错误:

带有返回值的RETURN语句不能在此上下文中使用。

如何在插入记录后从SQL server获取Identity值

SELECT SCOPE_IDENTITY();附加到正常的INSERT语句:

将最后一个串联替换为:

SQLString += "; SELECT SCOPE_IDENTITY();"

然后检索ID:

int ID = Convert.ToInt32(command.ExecuteScalar());

仔细查看OUTPUT子句。您可以从INSERT语句输出插入的ID。我发布的链接中有一些例子。

。。。或者只是运行

select @@identity