how to handle optional parameters in a update stored procedure

谁都会走 提交于 2019-12-24 18:30:26

问题


I need to write a generic procedure that set value for one column or no of a columns in a table depending on parameters. Any idea how to do it.


回答1:


I would guess you want something like:

CREATE PROC UpdateProc  
@RowID UNIQUEIDENTIFIER,
@Parameter1 NVARCHAR(50) NULL,
@Parameter2 INT NULL

AS

SET NOCOUNT ON
GO

IF @Parameter1 IS NOT NULL
BEGIN 
    UPDATE MyTable
    SET Column1 = @Parameter1
    WHERE ID = @RowID
END

IF @Parameter2 IS NOT NULL
BEGIN
    UPDATE MyTable
    SET Column2 = @Parameter2
    WHERE ID = @RowID
END

It doesn't feel particularly elegant but if you don't know/can't guarantee which parameters will be passed I don't know of a better way than to test them in turn for NULL.



来源:https://stackoverflow.com/questions/2424244/how-to-handle-optional-parameters-in-a-update-stored-procedure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!