通过具有可变参数的存储过程更新表

时间:2014-02-14 11:36:30

标签: sql-server tsql stored-procedures

为了便于使用,我有一些存储过程,它们具有SELECT语句的可选参数,如下所示:

CREATE PROCEDURE stpProcedure
    @Variable1 INT = NULL,
    @Variable2 INT = NULL,
    @Variable3 INT = NULL,
    @NumberToReturn INT = 1000
AS
BEGIN
    SELECT TOP (@NumberToReturn)    Column1,
                                    Column2,
                                    Column3,
                                    Column4
    From                            Table1
    WHERE                           (@Variable1 IS NULL OR Column1 = @Variable1)
    AND                             (@Variable2 IS NULL OR Column2 = @Variable2)
    AND                             (@Variable3 IS NULL OR Column3 = @Variable3)
END
GO

有没有办法将此技术用于更新语句?即我想根据特定表的存储过程输入更新一个或多个列。我想要做的一个例子如下:

CREATE PROCEDURE stpUpdate
    @Variable1 INT = NULL,
    @Variable2 INT = NULL,
    @Variable3 INT = NULL,
    @Variable4 INT,
    @NumberToReturn INT = 1000
AS
BEGIN
    Update      Table1
    SET         Column1 = @Variable1,
                Column2 = @Variable2,
                Column3 = @Variable3
    From        Table1
    Where       Column4 = @Variable4
END
GO

2 个答案:

答案 0 :(得分:1)

您可以使用 COALESCE() 函数来构建此类更新语句

CREATE PROCEDURE stpUpdate
    @Variable1 INT = NULL,
    @Variable2 INT = NULL,
    @Variable3 INT = NULL,
    @Variable4 INT,
    @NumberToReturn INT = 1000
AS
BEGIN
    Update      Table1
    SET         Column1 = COALESCE(@Variable1,Column1),
                Column2 = COALESCE(@Variable2,Column2),
                Column3 = COALESCE(@Variable3,Column3)

    Where       Column4 = COALESCE(@Variable4,Column4)
END
GO

答案 1 :(得分:0)

我比sql server更了解postgres,可能下面的这句话可以帮助你。

UPDATE table1 SET Column1 = (CASE WHEN (Column1 IS NULL || Column1==@Variable1) THEN @Variable1 else Column1),
Column2 = (CASE WHEN (Column2 IS NULL || Column2 == @Variable2) THEN @Variable2 else Column2),
Column3 = (CASE WHEN (Column3  IS NULL || Column3 == @Variable3) THEN @Variable3 else Column3)