我有以下适用于Oracle的代码:
OracleCommand command = conn.CreateCommand(); // conn is my connection
string sql = "INSERT INTO table_name (ID, NAME, GENDER) VALUES (1, 'JOHN', 'M') RETURNING ID INTO :returnedId";
command.CommandText = sql;
command.Parameters.Add(new OracleParameter("returnedId", OracleDbType.Decimal));
command.ExecuteNoQuery();
我需要将它移植到SQL Server。这就是我正在做的事情:
SqlCommand command = conn.CreateCommand(); // conn is my connection
string sql = "INSERT INTO table_name (Id, Name, Gender) OUTPUT Inserted.Id As returnedId VALUES (1, "JOHN", "M")";
command.CommandText = sql;
command.Parameters.Add(new SqlParameter("returnedId", SqlDbType.Decimal));
command.ExecuteNoQuery();
该代码给出了以下错误:
参数化查询需要未提供的参数:@returnedId
将RETURNING
和:returnedId
子句从Oracle迁移到SQL Server的正确方法是什么?
我已尝试OUTPUT Inserted.Id As @returnedId
以及将SqlParameter
更改为"@returnedId"
但未成功。
答案 0 :(得分:5)
OUTPUT SQL Server 相当于RETURNING INTO。
INSERT INTO table_name (ID, NAME, GENDER)
OUTPUT INSERTED.ID
VALUES (1, 'JOHN', 'M') ;
C#:
Int32 outputID = (Int32)command.ExecuteScalar();