我在数据库中添加一条带有identity值的记录。我要在插入后获取身份值。我不想通过存储过程做到这一点。
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语句不能在此上下文中使用。
附加SELECT SCOPE_IDENTITY();到您的普通INSERT语句:
SELECT SCOPE_IDENTITY();
将最后一个串联替换为:
SQLString += "; SELECT SCOPE_IDENTITY();"
然后检索ID:
int ID = Convert.ToInt32(command.ExecuteScalar());