views:

49

answers:

4

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!

+7  A: 

Try this.

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=ISNULL(@ordering,ordering), 
        title=ISNULL(@title,title), 
        content=ISNULL(@content, content)
    WHERE id=@id
END

It might also be worth adding an extra part to the WHERE clause, if you use transactional replication then it will send another update to the subscriber if all are NULL, to prevent this.

WHERE id=@id AND (@ordering IS NOT NULL OR
                  @title IS NOT NULL OR
                  @content IS NOT NULL)
Chris Diver
Coalesce() is best practice, not IsNull()
Emtucifor
It is not best practice, that is you subjective preference as `COALESCE` is ANSI. Both functions act differently, to say that you should always use one over the other as best practice is wrong. But in this case they act the same.
Chris Diver
A: 
UPDATE tbl_ClientNotes 
SET ordering=@ordering, title=@title, content=@content 
WHERE id=@id 
AND @ordering IS NOT NULL
AND @title IS NOT NULL
AND @content IS NOT NULL

Or if you meant you only want to update individual columns you would use the post above mine. I read it as do not update if any values are null

FlyingStreudel
This will never update unless all 3 parameters are provided.
Fosco
Indeed, I even wrote that.
FlyingStreudel
+3  A: 
   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.

Martin Smith
+3  A: 

One Idea:

UPDATE tbl_ClientNotes
SET ordering=ISNULL(@ordering, ordering), title=ISNULL(@title, title),  content=ISNULL(@content, content)
WHERE id=@id
Ian Jacobs