Oracle的RETURNING INTO:使用SQL Server的等效变量

时间:2014-05-06 02:26:30

标签: c# sql sql-server oracle sql-returning

我有以下适用于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"但未成功。

1 个答案:

答案 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();