我有以下解决方案
Select Col1 = Case when Col1 is null then 'update'
else Col1
,Col2 = Case when Col1 is null then Col2
when Col2 is null then 'update'
else Col2
,Col3 = Case when Col2 is null then Col3
when Col3 is null then 'update'
else Col3
.... and so on
只是想知道是否有人有更好的解决方案。
答案 0 :(得分:1)
您的解决方案不正确。
SQL不能以这种方式工作,您需要检查所有前面的列。
(而您忘了ENDs
CASEs
DECLARE @T TABLE(
col1 sysname NULL
,col2 sysname NULL
,col3 sysname NULL
)
INSERT INTO @T
SELECT NULL, 'N', NULL
-- Incorrect
Select Col1 = Case when Col1 is null then 'update'
else Col1
END
,Col2 = Case when Col1 is null then Col2
when Col2 is null then 'update'
else Col2
END
,Col3 = Case when Col2 is null then Col3
when Col3 is null then 'update'
else Col3
END
FROM @T
-- Dull, but correct
SELECT
Col1 = ISNULL(Col1, 'update')
,col2 = CASE
WHEN Col1 IS NOT NULL
AND Col2 IS NULL
THEN 'update'
ELSE Col2
END
,col3 = CASE
WHEN Col1 IS NOT NULL
AND Col2 IS NOT NULL
AND Col3 IS NULL
THEN 'update'
ELSE Col3
END
FROM @T