4

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.

1 Answer 1

5

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Can you please better elaborate ? I´ve added the table creation but still not working... Remember I´m using C# code to get the Id data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.