2014-02-14 54 views
1

爲了便於使用,我已存儲的程序,這對SELECT statments像下面的可選參數的存儲過程更新的表:通過與可變參數

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 
+0

爲什麼不只是你的更新聲明以及條件和解釋的地方。 – KumarHarsh

回答

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 
+0

+1輝煌我沒有想到這一點。 –

+0

沒有問題很高興它幫助:) –

0

我知道更多的Postgres於SQL Server的,可下面的這個陳述可以幫助你。

UPDATE table1 SET Column1 = (CASE WHEN (Column1 IS NULL || [email protected]) 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)