I have a multi-statement SQL query that takes place within a SqlTransaction as follows:
string sName = "";
string sNumber = "";
string sFirstName = "";
string sqlQuery1 = @"INSERT INTO myTable(Name, Number) VALUES (@_Name, @_Number)";
string sqlQuery2 = @"INSERT INTO myOtherTable( ID, FirstName) VALUES ( @_ID, @_First )";
SqlConnection conn = new SqlConn(***);
conn.Open();
SqlTransaction transaction;
SqlCommand command1 = new SqlCommand(sqlQuery1, conn, transaction);
SqlCommand command2 = new SqlCommand(sqlQuery2, conn, transaction);
command1.Parameters.Add("@_Name", SqlDbType.NVarChar, 255).Value = sName;
command1.Parameters.Add("@_Number", SqlDbType.NVarChar, 255).Value = sNumber;
int? returnedID = (int?)command1.ExecuteScalar();
command2.Parameters.Add("@_ID", SqlDbType.Int).Value = (int)returnedID; <--- Error
command2.Parameters.Add("@_First", SqlDbType.NVarChar, 255).Value = sFirstName;
command2.ExecuteNonQuery();
transaction.Commit();
At the line I marked as an error, I get an error during execution about "The parameterized query expects the parameter @_ID which was not supplied.
Now, assuming I have no typos while simplifying my code to this example, why am I receiving a null value in returnedID for a properly executed statement? When I just run the statement on its own in a query, I get no errors and it returns successful. Why null when running it in this transaction? Thanks!
Edit: I purposely left off a try{} catch from this as it wasn't relevant to the question I had. Otherwise, I just forgot about the IDENTITY_SCOPE() that I needed in the Insert query since there would otherwise be no return value.