我在数据库中添加了一条记录,其值为identity
。我想在插入后得到身份值。我不想通过存储过程来做到这一点。如何在插入记录后从SQL服务器获取标识值
这是我的代码:
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;
}
,但我得到这个错误:
A RETURN statement with a return value cannot be used in this context.
你有没有尝试谷歌? – Stokedout 2014-10-06 09:27:58
我希望这只是“样本”代码,并不适用于任何类型的生产系统。如果你打算真实地使用它,请查看查询中使用的参数而不是String.Format,并且至少在使用sql连接时使用“using”,以便它关闭并处理连接。 – 2014-10-06 09:48:33