Trying to figure out if it's best to use ExecuteScalar
or ExecuteNonQuery
if I want to return the identity column of a newly inserted row. I have read this question and I understand the differences there, but when looking over some code I wrote a few weeks ago (whilst heavily borrowing from this site) I found that in my inserts I was using ExecuteScalar
, like so:
public static int SaveTest(Test newTest)
{
var conn = DbConnect.Connection();
const string sqlString = "INSERT INTO dbo.Tests ( Tester , Premise ) " +
" VALUES ( @tester , @premise ) " +
"SET @newId = SCOPE_IDENTITY(); ";
using (conn)
{
using (var cmd = new SqlCommand(sqlString, conn))
{
cmd.Parameters.AddWithValue("@tester", newTest.tester);
cmd.Parameters.AddWithValue("@premise", newTest.premise);
cmd.Parameters.Add("@newId", SqlDbType.Int).Direction = ParameterDirection.Output;
cmd.CommandType = CommandType.Text;
conn.Open();
cmd.ExecuteScalar();
return (int) cmd.Parameters["@newId"].Value;
}
}
}
This works fine for what I need, so I'm wondering
- Whether I should be using
ExecuteNonQuery
here because it is "more proper" for doing inserts? - Would retrieving the identity value be the same either way since I'm using an output parameter?
- Are there any performance hits associated with one way or the other?
- Is there generally a better way to do this overall?
I'm using Visual Studio 2010, .NET 4.0, and SQL Server 2008r2, in case that makes any difference.
ExecuteNonQuery
"more proper"? (2) have you considered using stored procedures? If not, why not? It would definitely help clean up all of the ad hoc SQL you're putting into your app - which, when you have to change it, means you have to re-compile and re-deploy the app. – VigenSELECT SCOPE_IDENTITY();
then usereturn (int)cmd.ExecuteScalar();
– OverlapExecuteScalar
because i useSELECT SCOPE_IDENTITY
without an output parameter, hence retrieve a single value which is the purpose ofExecuteScalar
. https://mcmap.net/q/152269/-return-value-from-sql-server-insert-command-using-c – MerrymerryandrewSystem.InvalidCastException: Specified cast is not valid
when I try to run it. It worked before with the output parameter... any ideas why it couldn't do the cast here? I also tried assigning it to anint
variable before the return, but same result. – Daileynumeric
) – Merrymerryandrewnumeric
thing, esp since my identity column was anint
(and it worked w/o casting on the output param). I even went and found the reason why. – Dailey