如何在WHERE子句中设置值。我正在使用SQL Server MS。
DECLARE @Value INT;
SOMEPOINT:
INSERT $(TempTable)(Value, ...)
SELECT DISTINCT @Value, ...
FROM $(TempTable) t1
JOIN $(TempTable) t2 ON
t2.smth1 = t1.smth2
WHERE
@Value = CASE WHEN t1.Value IS NULL THEN t2.Value ELSE t1.Value // so i want here to set the @Value value instead of ckecking it
END
IF @@ROWCOUNT > 0 GOTO SOMEPOINT
我尝试了很多东西,没有任何帮助。如果在WHERE子句中不可能做到这一点我应该改变什么呢?
答案 0 :(得分:2)
您不能在WHERE
子句中设置变量,但可以使用计算值的表达式:
INSERT $(TempTable)(Value, ...)
SELECT DISTINCT
CASE WHEN t1.Value IS NULL THEN t2.Value ELSE t1.Value END AS Value
, ...
FROM $(TempTable) t1
JOIN $(TempTable) t2 ON
t2.smth1 = t1.smth2
这使Value
成为"计算列"您的SELECT DISTINCT
条款,使其符合插入条件。
注意: COALESCE
更适合您提供NULL
(Gordon Linoff)的默认值
INSERT $(TempTable)(Value, ...)
SELECT DISTINCT
COALESCE(t1.Value, t2.Value) AS Value
, ...
FROM $(TempTable) t1
JOIN $(TempTable) t2 ON
t2.smth1 = t1.smth2