在SQL中使用没有ELSE条件的IF

时间:2017-11-08 15:00:48

标签: sql sql-server if-statement

我正在尝试使用以下查询来仅在@rowcount大于0时更新某些数据。但是,即使@RowCount为0,它也会执行更新语句。有人可以帮忙解决这里的错误吗?如果@RowCount为0,我不想做任何事。

我正在使用SQL Server 2014。

    TRUNCATE TABLE Count1
    DECLARE @RowCount AS INT

    --insert data in a temporary table
    SELECT YEAR, S_ID
    into #Count1 FROM
    (SELECT DISTINCT D.YEAR, S_ID FROM SALES S JOIN TRANSACTIONS PT
    ON S.COMBINED_TXN_ID = PT.S_ID AND PT.TRANSACTION_TYPE = 'BILLING'
    JOIN DATE D ON D.DAY = S.DAY AND PT.DAY = S.DAY
    WHERE
    S.SALES_CUSTOMER    !=   PT.CUSTOMER)Counter1;

    --Store the rowcount in a temporary variable
    SET @RowCount = (SELECT Count(*) FROM #Count1) 

    --Fix the data with differences only if count>0
    IF @@ROWCOUNT > 0
    BEGIN
    UPDATE SALES
    SET SALES_CUSTOMER =  PT.CUSTOMER
    FROM SALES S
    JOIN TRANSACTIONS PT ON  S.COMBINED_TXN_ID = PT.S_ID
    JOIN DATE D ON D.DAY = S.DAY AND PT.DAY = S.DAY
    WHERE
    S_ID IN (SELECT S_ID FROM #Count1) 
    END;

4 个答案:

答案 0 :(得分:3)

@@ROWCOUNT返回受最后一个语句影响的行数。

使用您自己的变量@RowCount

更改系统变量@@ ROWCOUNT
--Store the rowcount in a temporary variable
SET @RowCount = (SELECT Count(*) FROM #Count1) 

--Fix the data with differences only if count>0
IF  @RowCount > 0

答案 1 :(得分:2)

您将自己定义的本地变量>>> import diss >>> l = [1,2] >>> def foo(): ... global l ... x = l[1] ... >>> dis.dis(foo) 3 0 LOAD_GLOBAL 0 (l) 3 LOAD_CONST 1 (1) 6 BINARY_SUBSCR 7 STORE_FAST 0 (x) 10 LOAD_CONST 0 (None) 13 RETURN_VALUE >>> 与您为自己定义的全局变量@RowCount混淆(您无法设置)。< / p>

所以简单地参考正确的变量。更好的是:重命名你的局部变量以避免这种混淆。

您甚至根本不需要@@ROWCOUNT,因为如果if为空,则无法执行更新,因为没有记录可以履行#Count1 } clause(where)。

答案 2 :(得分:1)

您可以跳过所有临时表和检查,然后进行更新。这样的事情应该和你发布的所有代码一样。

UPDATE S
SET SALES_CUSTOMER = PT.CUSTOMER
FROM SALES S
JOIN S PT ON S.COMBINED_TXN_ID = PT.S_ID
             AND PT.TRANSACTION_TYPE = 'BILLING'
JOIN DATE D ON D.DAY = S.DAY 
            AND PT.DAY = S.DAY
WHERE  S.SALES_CUSTOMER != PT.CUSTOMER

答案 3 :(得分:1)

如果您希望使用相同的变量,则声明使用@rowcount

DECLARE @recordCount INT

--insert data in a temporary table
SELECT YEAR
    ,S_ID
INTO #Count1
FROM (
    SELECT DISTINCT D.YEAR
        ,S_ID
    FROM SALES S
    INNER JOIN TRANSACTIONS PT
        ON S.COMBINED_TXN_ID = PT.S_ID
            AND PT.TRANSACTION_TYPE = 'BILLING'
    INNER JOIN DATE D
        ON D.DAY = S.DAY
            AND PT.DAY = S.DAY
    WHERE S.SALES_CUSTOMER != PT.CUSTOMER
    ) Counter1;

--Store the rowcount in a temporary variable
SELECT @recordCount = count(*)
FROM #Count1

--Fix the data with differences only if count>0
IF (@recordCount > 0)
BEGIN
    UPDATE SALES
    SET SALES_CUSTOMER = PT.CUSTOMER
    FROM SALES S
    INNER JOIN TRANSACTIONS PT
        ON S.COMBINED_TXN_ID = PT.S_ID
    INNER JOIN DATE D
        ON D.DAY = S.DAY
            AND PT.DAY = S.DAY
    WHERE S_ID IN (
            SELECT S_ID
            FROM #Count1
            )
END