如果一行中的 n 列之一包含非空值,返回 CHAR(1) 指示符 Y/N 的最简洁方法是什么?
在本例中,性能很重要,但不是首要考虑因素。
最简单的方法似乎是:
SELECT CASE WHEN (C.TerminatedDate IS NULL
AND C.SelfClosedDate IS NULL
AND ...)
THEN 'Y'
ELSE 'N' END AS 'OpenInd'
FROM Customers C
好奇是否有更好的方法;了解 COALESCE():
SELECT CASE WHEN COALESCE (C.TerminatedDate, C.SelfClosedDate, ...) IS NULL
THEN 'Y'
ELSE 'N' END AS 'OpenInd'
FROM Customers C
有更好的方法吗?
数据库服务器是SQL Server 2008。
最佳答案
由于没有人建议,并且问题要求简洁
..
对于相同的数据类型,直接 COALESCE 是最好的
coalesce(a,b,c,d) is not null
如果您要处理不同的数据类型,请尝试修改后的 COALESCE
coalesce(LEFT(a,1),LEFT(b,1),LEFT(c,1)) is not null
示例:
create table abc (a int, b datetime, c varchar(max), d image)
insert into abc select 1, GETDATE(), '', null
insert into abc select 1, null, '', null
insert into abc select 1, null, '', 0x123123
insert into abc select null, null, '', 0x123123
insert into abc select null, GETDATE(), '', 0x123123
insert into abc select null, null, null, null
insert into abc select 88, GETDATE()+3, null, null
insert into abc select 88, GETDATE()+3, 'gdasdf', null
insert into abc select null, null, '222', 0x123123
insert into abc select null, null, 'abcdef', 0x123123
select *, case when coalesce(LEFT(a,1),LEFT(b,1),LEFT(c,1)) is not null then 'N' else 'Y' end
from abc
如果您不使用 VARCHAR(MAX) 或 IMAGE 等外来类型,则可以将 SQL_VARIANT 与 COALESCE 结合使用
create table abc (a int, b datetime, c varchar(10), d image)
insert into abc select 1, GETDATE(), '', null
insert into abc select 1, null, '', null
insert into abc select 1, null, '', 0x123123
insert into abc select null, null, '', 0x123123
insert into abc select null, GETDATE(), '', 0x123123
insert into abc select null, null, null, null
insert into abc select 88, GETDATE()+3, null, null
insert into abc select 88, GETDATE()+3, 'gdasdf', null
insert into abc select null, null, '222', 0x123123
insert into abc select null, null, 'abcdef', 0x123123
select *, case when coalesce(convert(sql_variant,a),b,c) is not null then 'N' else 'Y' end
from abc
关于sql-server - 如果一列或多列包含非空值,返回 Y/N 的最有效方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5236372/