Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/268.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/84.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 插入记录后如何从SQL server获取标识值_C#_Sql_.net_Sql Server_Identity - Fatal编程技术网

C# 插入记录后如何从SQL server获取标识值

C# 插入记录后如何从SQL server获取标识值,c#,sql,.net,sql-server,identity,C#,Sql,.net,Sql Server,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 = " 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语句不能在此上下文中使用


追加
选择范围\标识()到您的常规INSERT语句:

将最后一个连接替换为:

SQLString += "; SELECT SCOPE_IDENTITY();"
然后检索ID:

int ID = Convert.ToInt32(command.ExecuteScalar());
好好看看这张照片。您可以从INSERT语句中输出插入的ID。我发布的链接中有一些例子。

。。。还是就跑

select @@identity

我希望这只是“示例”代码,不用于任何类型的生产系统。如果您打算将其用于实际,请研究在查询中使用参数而不是String.Format,并至少使用“using”使用sql连接时,它将关闭并处理连接。您应该在回答中说明,
输出
对行有效,这样您就可以从语句中检索所有插入的ID
(而不仅仅是插入的ID)。@DrCopyPaste,那么如果我们想要所有ID,我们怎么做呢?