views:

48

answers:

3

I have to write a update stored procedure. I will be asking paramters for all the columns ( Except id). User won’t be sending all the paramaters all the times. He wants to send paramter value NULL so don’t update that column, the columns he wants to update there will be valid value. How do I Write a stored proc for this. Basically I will have to check each parameter value and if it’s not null then only update that column. Thanks in advance!!

A: 
Create Procedure MyProc ( @Param1 int,
@Param2 varchar(20),
@Param3 int = NULL)
As
Begin

-- the sp

End

See @Param3 for how you specify a default value.

Thomas Lundström
I don't want to set it to NULL. When user sets that parameter to NULL I am not supposed to update that col. I have to check each parameter value and if it's not NULL then only update those cols. Leave the cols ( Do not update) if value set to NULL by user.
Ah, my bad. Then you want to use COALESCE as noted above.
Thomas Lundström
+2  A: 

Use COALESCE, which will set the column to a new value if it is NOT NULL, or back to the same original value otherwise:

UPDATE  MyTable

SET     MyColumn1 = COALESCE(@MyColumn1, MyColumn1),
        MyColumn2 = COALESCE(@MyColumn2, MyColumn2),
        MyColumn3 = COALESCE(@MyColumn3, MyColumn3)

WHERE   ID = @ID
van
Thanks I will try it and let you know.
Perfect!! this worked. Thank you very much. Am I supposed to mark as accepted answer or something. Please let me know.
+2  A: 

try:

CREATE PROCEDURE YourUpdate
(
    @Param_PK    int
   ,@Param1      varchar(10)=NULL
   ,@Param2      int=NULL
   ,@Param3      datetime=NULL
)


UPDATE YourTable
    SET col1=COALESCE(@Param1,col1)
       ,col2=COALESCE(@Param2,col2)
       ,col3=COALESCE(@Param3,col3)
    WHERE PK=@Param_PK

go3
KM
note that the "=NULL" syntax in the parameter declaration allows you to call the procedure without specifying that parameter and that the procedure will default it to the "=x", which is NULL in this case. So, `EXEC YourUpdate 123` is valid, as is `EXEC YourUpdate 123,'abc',5,'1/1/2010'` as is `EXEC YourUpdate @Param_PK=123,@Param2=5`
KM

related questions