I would like to have a stored procedure that will update the values in the table row depending on whether the parameters are provided. For example, I have a situation where I want to update all values, but also a situation where only two values need to be updated. I was hoping that I could do this with only one procedure, instead of writing two, which I especially dislike. The best I managed to come up with is something like the following:
CREATE PROCEDURE dbo.UpdatePerson
@PersonId INT,
@Firstname VARCHAR(50) = NULL,
@Lastname VARCHAR(50) = NULL,
@Email VARCHAR(50) = NULL
AS
BEGIN
SET NOCOUNT ON
UPDATE Person
Set
Firstname = COALESCE(@Firstname, Firstname),
Lastname = COALESCE(@LastName, Lastname),
Email = COALESCE(@Email, Email)
WHERE PersonId = @PersonId
END
I understand that the values will be updated every time in any case, which is not ideal. Is this an effective way to achieve this, or can it be done better?
source
share