I am having issues trying to get the syntax correct for my C# 2008 asp.net code. I need to get a return value (Select @@Identity) from my stored procedure
My C# code is:
SqlConnection conn = new SqlConnection(strConn);
string sql = "usp_ClientProfile_Header";
SqlCommand cmdHeader = new SqlCommand(sql, conn);
cmdHeader.CommandType = CommandType.StoredProcedure;
cmdHeader.Parameters.Add(new SqlParameter("@FirstName", SqlDbType.VarChar, 50));
cmdHeader.Parameters["@FName"].Value = txtFName.Text.Trim();
cmdHeader.Parameters.Add(new SqlParameter("@LastName", SqlDbType.VarChar, 50));
cmdHeader.Parameters["@LName"].Value = txtLName.Text.Trim();
cmdHeader.Parameters.Add(new SqlParameter("@EmailAddress", SqlDbType.VarChar, 100));
cmdHeader.Parameters["@Email"].Value = txtEMail.Text.Trim();
cmdHeader.Parameters.Add(new SqlParameter("@Address1", SqlDbType.VarChar, 255));
cmdHeader.Parameters["@Address1"].Value = txtAddress1.Text.Trim();
cmdHeader.Parameters.Add(new SqlParameter("@City", SqlDbType.VarChar, 50));
cmdHeader.Parameters["@City"].Value = txtCity.Text.Trim();
cmdHeader.Parameters.Add(new SqlParameter("@State", SqlDbType.VarChar, 50));
cmdHeader.Parameters["@State"].Value = txtState.Text.Trim();
cmdHeader.Parameters.Add(new SqlParameter("@ZipCode", SqlDbType.VarChar, 12));
cmdHeader.Parameters["@Postal_Code"].Value = txtZip.Text.Trim();
The next line in my code needs to be the "ParameterDirection.ReturnValue" but I can't seem to get the syntax correct.
Any ideas?
To capture a RETURN VALUE (returned by SQL using the RETURN({number}) syntax) use:
cmdHeader.Parameters.Add("@ReturnValue", SqlDbType.Int, 4).Direction = ParameterDirection.ReturnValue;
Also, you should probably be using SCOPE_IDENTITY() instead of @@IDENTITY
Edit:
So your sproc would do something like:
DECLARE @NewId INTEGER
INSERT SomeTable(FieldA) VALUES ('Something')
SELECT @NewId = SCOPE_IDENTITY()
RETURN (@NewId)
And your C# code to retrieve that value would be:
int newId = cmdHeader.Parameters[@ReturnValue].value;
Edit 2:
Ok, the original question confused the issue as the "return value" is a different thing to what you're actually doing which is returning a single column resultset.
So, instead DON'T add a ReturnValue parameter at all. Just use ExecuteScalar() using your original SqlCommand setup as below:
int newId = Convert.ToInt32(cmdHeader.ExecuteScalar());
SqlParameter parameterReturnValue = new SqlParameter("ReturnValue", SqlDbType.Int, 4);
parameterReturnValue.Direction = ParameterDirection.ReturnValue;
cmdHeader.Parameters.Add(parameterReturnValue);
//Execute your command
cmdHeader.ExecuteNonQuery();
//Get the return value
int returnvalue = (int)myCommand.Parameters["ReturnValue"].Value;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With