gpt4 book ai didi

sql - 在 SQL 中使用不带 ELSE 条件的 IF

转载 作者:行者123 更新时间:2023-12-05 01:18:02 25 4
gpt4 key购买 nike

我只在@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;

最佳答案

@@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

关于sql - 在 SQL 中使用不带 ELSE 条件的 IF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47182933/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com