不是为了让这成为关于 COALESCE 和 NULLIF 的教程,而是为了证明@billinkc 在他的答案中提供的所有内容,这就是为什么它有效。(对不起,他回答时我正在研究解决方案)。将其放入 SSMS 并查看结果。不过,如上所示的简单更新会很好。
刚刚发现 SQL Fiddle 资源:
SQL Fiddle
--Setup the temp table
DECLARE @Parents TABLE (
ParentsId INT IDENTITY (1,1) PRIMARY KEY,
email varchar(max),
email2 varchar(max),
email3 varchar(max),
email4 varchar(max),
email5 varchar(max),
email6 varchar(max)
)
--This would be the pull from your real Parents Table.
INSERT INTO @Parents
SELECT
NULL,'test@domain.com',' ',NULL,NULL,NULL
UNION ALL
SELECT
NULL,' ',NULL,NULL,NULL,'test2@domain.com'
UNION ALL
SELECT
NULL,'',NULL,NULL,NULL,'test3@domain.com'
--Look at the data before we cleanse it
SELECT * FROM @Parents
--Take a look at what COALESCE looks like before the cleanse
SELECT ParentsId, COALESCE(email2,email3,email4,email5,email6) AS NewEmail FROM @Parents
--RUN the NULLIF
UPDATE @Parents SET
email2 = NULLIF(email2,' '),
email3 = NULLIF(email3,' '),
email4 = NULLIF(email4,' '),
email5 = NULLIF(email5,' '),
email6 = NULLIF(email6,' ')
SELECT * FROM @Parents
--Take a look at what COALESCE looks like after the cleanse
SELECT ParentsId, COALESCE(email2,email3,email4,email5,email6) AS NewEmail FROM @Parents