I am executing a stored procedure in C # (via vs2008) using ado.net using the ExecuteScalar command. The stored proc returns the key of the new record, but ExecuteScalar returns null. I look in the database and the record is really added. I can use the output parameter to get the value, but then I will not know why this did not work.
When I run sp in ssms, pkey is returned.
What am I doing wrong?
Here is the C # code:
public int SaveNewPerson(EPerson ePerson) { int newPersonPkey; SqlConnection cn = new SqlConnection(cnn.PersonData); using (cn) { try { SqlCommand cmd = new SqlCommand(); cmd.Connection = cn; cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "People.dbo.AddNewPerson"; cmd.Parameters.Add("@LastName", SqlDbType.VarChar, 150).Value = ePerson.LastName; cmd.Parameters.Add("@FirstName", SqlDbType.VarChar, 150).Value = ePerson.FirstName; cn.Open(); object result = cmd.ExecuteScalar(); newPersonPkey = int.Parse(result.ToString()); cn.Close(); } catch (Exception e) {
And this is sp:
PROCEDURE [dbo].[AddNewPerson] @FirstName varchar(50) ,@LastName varchar(50) AS BEGIN SET NOCOUNT ON; INSERT INTO [People].[dbo].[Persons] ( [FirstName] ,[LastName] ) VALUES ( @FirstName ,@LastName ) declare @persons_PKey int set @persons_PKey = @@IDENTITY return @persons_PKey end
source share