【发布时间】: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