【问题标题】:How to get Identity value from SQL server after insert record插入记录后如何从 SQL 服务器获取标识值
【发布时间】:2014-10-06 09:24:32
【问题描述】:

我在我的数据库中添加了一条具有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 语句。

【问题讨论】:

  • 我希望这只是“示例”代码,不用于任何类型的生产系统。如果您打算真正使用它,请考虑在查询中使用参数而不是 String.Format,并且在使用 sql 连接时至少使用“使用”,以便它会关闭并处理连接。

标签: c# sql .net sql-server identity


【解决方案1】:

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

将最后一个连接替换为:

SQLString += "; SELECT SCOPE_IDENTITY();"

然后检索ID:

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

【讨论】:

    【解决方案2】:

    好好看看OUTPUT clause。您可以从 INSERT 语句中输出您插入的 ID。我发布的链接中有示例。

    【讨论】:

    • 你应该在你的答案中包含OUTPUT适用于行,这样你就可以从语句中检索所有inserted IDs(不仅仅是inserted ID)。
    • @DrCopyPaste ,所以如果我们想要所有的 id ,我们该怎么做?
    【解决方案3】:

    ...或者只是运行

    select @@identity
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-24
      • 2012-09-03
      • 2013-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多