I put values ββin SQL Server using a stored procedure. The procedure will add the identifier to the added row. I need to return this identifier to my code.
Currently, I can get the output identifier in the OUTPUT window of Visual Studio, but it seems I cannot display it in my code. Here is a generic version of proc:
SQL
CREATE PROCEDURE dbo.DoSomething ( @var1 INT = NULL, @var2 INT = NULL, @var3 DATE = NULL ) AS BEGIN INSERT INTO atable ( vara, varb, varc ) VALUES ( @var1, @var2, @var3 ) RETURN SCOPE_IDENTITY() END
WITH#
int result = 0; /// create command SqlCommand cmd = new SqlCommand("DoSomething", this.OpenSqlConnection()); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@var1", thing.value1); cmd.Parameters.AddWithValue("@var2", thing.value2); cmd.Parameters.AddWithValue("@var3", thing.value3); /// send data to db result = (int)cmd.ExecuteScalar();
So, I get the error message: The object reference is not installed in the object instance. when it gets into (int) cmd.ExecuteScalar ().
Any ideas?
source share