Alex Rivera | Logout

Using UPDATE in stored procedure with optional parameters

Asked 2010-07-20T13:51:23.120
28

I have an SP like so (using SQL Server):

ALTER PROCEDURE [dbo].[sp_ClientNotes_update]
    @id uniqueidentifier,
    @ordering smallint = NULL,
    @title nvarchar(20) = NULL,
    @content text = NULL
AS
BEGIN
    SET NOCOUNT ON;
    UPDATE tbl_ClientNotes
    SET ordering=@ordering, title=@title, content=@content
    WHERE id=@id
END

I would like to only set the values if they are passed into the SP, i.e. not NULL. Can this be done?

This question seems to suggest the only way is using completely separate queries with conditionals, but for 3 optional parameters this would obviously be a nightmare!

Edit
Report

1 Answer

3
   UPDATE tbl_ClientNotes
    SET 
      ordering=ISNULL@ordering,ordering), 
      title=isnull(@title,title), 
      content=isnull(@content,content)
    WHERE id=@id

I think I remember seeing before that if you are updating to the same value SQL Server will actually recognize this and won't do an unnecessary write.

answered 2010-07-20T13:54:45.783

Your Answer