Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using UPDATE in stored procedure with optional parameters

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!

like image 519
DisgruntledGoat Avatar asked Jul 20 '10 13:07

DisgruntledGoat


People also ask

Can a stored procedure have optional parameters?

How to create stored procedure that accepts optional parameter in SQL Server? To create optional parameter in stored procedure, we set the parameter value to NULL while creating a stored procedure.

How can use optional parameter in stored procedure in SQL Server?

It is better to use the " = NULL" if you are adding a new optional parameter to an existing stored proc. The reason is, you may not be aware of ALL the code that calls this proc. Hence, unless you make it optional using the " = NULL", for all the places that you may have missed to pass in a value, it will break.

Can we use update in stored procedure?

A single stored procedure can be used to select, add, update, and delete data from a database table.


1 Answers

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) 
like image 75
Chris Diver Avatar answered Sep 23 '22 11:09

Chris Diver