I'm trying to get the output parameter of primary key which is ID. When I do the update query I get Null
. Can you please suggest a way to do this?
CREATE PROCEDURE sp_InsertTax
(@ID int output,
@TaxAuthorityID int,
@TaxClassificationID int,
@EntityID int,
@AppliesTo_TaxEntityTypeID int)
AS
IF EXISTS (SELECT * FROM Tax
WHERE TaxAuthorityID = @TaxAuthorityID
AND TaxClassificationID = @TaxClassificationID
AND EntityID = @EntityID
AND AppliesTo_TaxEntityTypeID = @AppliesTo_TaxEntityTypeID)
BEGIN
UPDATE Tax
SET TaxAuthorityID = @TaxAuthorityID,
TaxClassificationID = @TaxClassificationID,
EntityID = @EntityID,
AppliesTo_TaxEntityTypeID = @AppliesTo_TaxEntityTypeID
WHERE ID = @ID
END
ELSE
BEGIN
IF @ID IS NULL
BEGIN
INSERT INTO Tax(TaxAuthorityID, TaxClassificationID, EntityID, AppliesTo_TaxEntityTypeID)
VALUES (@TaxAuthorityID, @TaxClassificationID, @EntityID, @AppliesTo_TaxEntityTypeID)
SET @ID = Scope_Identity()
END
END
GO
The below is my ADO.NET code to call the update stored procedure:
public int InsertFederalTax(int ClassificID, int appliesTo)
{
int tax_id = 0;
Sqlconn.Open();
SqlCommand cmd = new SqlCommand("sp_InsertTax", Sqlconn);
cmd.CommandType = CommandType.StoredProcedure;
var returnparameter = cmd.Parameters.AddWithValue("ID", SqlDbType.Int);
returnparameter.Direction = ParameterDirection.Output;
cmd.Parameters.Add("@TaxAuthorityID", SqlDbType.Int).Value = 1;
cmd.Parameters.Add("@TaxClassificationID", SqlDbType.Int).Value = ClassificID;
cmd.Parameters.Add("@EntityID", SqlDbType.Int).Value = 0;
cmd.Parameters.Add("@AppliesTo_TaxEntityTypeID", SqlDbType.Int).Value = appliesTo;
cmd.ExecuteNonQuery();
if (!(returnparameter.Value is DBNull))
tax_id = Convert.ToInt32(returnparameter.Value);
Sqlconn.Close();
return tax_id;
}