Technical Article

Preventing accidental overwrites with update SPs

,

Say you wanted to create an SP for updating records in a database.  How would you do this in such a way as to allow your users to edit only a subset of fields in the record, without overwriting the other fields, and without requiring verbose IF blocks and CASE statements in your code?

Simple.  Use the ISNULL function when assigning values to your variables, as shown here:

CREATE PROCEDURE UpdateAddress 
@ContactID int,
@AddressType int,
@StreetNumber varchar(20) = NULL,
@StreetName varchar(100) = NULL,
@Suite varchar(20) = NULL,
@City varchar(50) = NULL,
@StateProvince varchar(50) = NULL,
@PostalCode varchar(30) = NULL
@Country varchar(50) = NULL

AS

UPDATE Address
SET
StreetNumber = ISNULL(@StreetNumber, StreetNumber),
SteetName = ISNULL(@StreetName, StreetName),
Suite = ISNULL(@Suite, Suite),
City = ISNULL(@City, City),
StateProvince = ISNULL(@StateProvince, StateProvince),
PostalCode = ISNULL(@PostalCode, PostalCode),
Country = ISNULL(@Country, Country)
WHERE
ContactID = @ContactID
AND
AddressType = @AddressType

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating