OUTPUT is SQL Server's equivalent to RETURNING INTO.
INSERT INTO table_name (ID, NAME, GENDER)
OUTPUT INSERTED.ID
VALUES (1, 'JOHN', 'M') ;
And C# :
Int32 outputID = (Int32)command.ExecuteScalar();
Question
I have the following code that works on 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();
I need to port that to SQL Server. This is what I'm doing:
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();
That code gives me the following error:
the parameterized query expects the parameter which was not supplied: @returnedId
What's the correct way to migrate the RETURNING
and the :returnedId
clauses from Oracle to SQL Server ?
I've tried OUTPUT Inserted.Id As @returnedId
as well as changing the SqlParameter
to "@returnedId"
with no success.
La solution
OUTPUT is SQL Server's equivalent to RETURNING INTO.
INSERT INTO table_name (ID, NAME, GENDER)
OUTPUT INSERTED.ID
VALUES (1, 'JOHN', 'M') ;
And C# :
Int32 outputID = (Int32)command.ExecuteScalar();