Browsed some answers and doesn't appear to be working for me.
I need the ID field of a table to be returned so I can use it in a different part of the program, I've tried using
Convert.ToInt32(sqlComm.ExecuteScalar());
But no luck, and same for
Convert.ToInt32(sqlComm.Parameters["ID"].Value);
And both return 0, even though the record does get inserted into the table.
I'll dump the code below, can anyone see what I'm doing wrong?
using (SqlConnection sqlConnect = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
using (SqlCommand sqlComm = new SqlCommand("up_Insert_Address", sqlConnect))
{
sqlComm.CommandType = CommandType.StoredProcedure;
sqlComm.Parameters.Add("@AddressID", SqlDbType.BigInt).Direction = ParameterDirection.Output;
sqlComm.Parameters.Add("@AddressLineOne", SqlDbType.NVarChar, 40).Value = address.AddressLineOne;
try
{
sqlComm.Connection.Open();
return Convert.ToInt32(sqlComm.ExecuteScalar());
}
catch (SqlException)
{
}
finally
{
sqlComm.Connection.Close();
}
}
}
And Stored Procedure:
@AddressID Bigint OUTPUT,
@AddressLineOne NVarChar(40)
AS
BEGIN
BEGIN TRY
INSERT INTO Address
(
AddressLineOne
)
VALUES
(
@AddressLineOne
)
SET @AddressID = SCOPE_IDENTITY();
END TRY
BEGIN CATCH
DECLARE @Err nvarchar(500)
SET @Err = ERROR_MESSAGE()
RAISERROR(@Err, 16, 1)
END CATCH
END