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!
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.
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.
A single stored procedure can be used to select, add, update, and delete data from a database table.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With