D
Dylan Parry
Hi folks,
This is really confusing me. I am trying to insert a row into a
database, and then use scope_identity() to return the value of the ID
column for the record I have just created. The code I am using is
something like the below:
--- Start ---
// Build query
this.command = this.connection.CreateCommand();
this.command.CommandText = "INSERT INTO table (foo) VALUES(@foo)";
// Query parameters
this.command.Parameters.Add("@foo", SqlDbType.VarChar).Value = "bar";
// Execute query
int rows = this.command.ExecuteNonQuery();
// Clear the parameters
this.command.Parameters.Clear();
// Create a new command to get the ID
this.command.CommandText = "SELECT scope_identity()";
int id = Convert.ToInt32(this.command.ExecuteScalar());
---- End ----
But when I run this code I get an error telling me that I cannot cast to
Int32 from DBNull.Value. Obviously this is correct, but why am I not
actually getting the value of the ID column returned by the latter
query?
Also, if I change "scope_identity()" to "@@identity" I get errors about
some of my parameters not being defined, when they clearly are. This
also occurs if I attempt to combine the INSERT and SELECT statements
into the one command.
Any ideas?
This is really confusing me. I am trying to insert a row into a
database, and then use scope_identity() to return the value of the ID
column for the record I have just created. The code I am using is
something like the below:
--- Start ---
// Build query
this.command = this.connection.CreateCommand();
this.command.CommandText = "INSERT INTO table (foo) VALUES(@foo)";
// Query parameters
this.command.Parameters.Add("@foo", SqlDbType.VarChar).Value = "bar";
// Execute query
int rows = this.command.ExecuteNonQuery();
// Clear the parameters
this.command.Parameters.Clear();
// Create a new command to get the ID
this.command.CommandText = "SELECT scope_identity()";
int id = Convert.ToInt32(this.command.ExecuteScalar());
---- End ----
But when I run this code I get an error telling me that I cannot cast to
Int32 from DBNull.Value. Obviously this is correct, but why am I not
actually getting the value of the ID column returned by the latter
query?
Also, if I change "scope_identity()" to "@@identity" I get errors about
some of my parameters not being defined, when they clearly are. This
also occurs if I attempt to combine the INSERT and SELECT statements
into the one command.
Any ideas?