sql-server - 如果一列或多列包含非空值,返回 Y/N 的最有效方法是什么?

标签 sql-server null

如果一行中的 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/

相关文章:

sql - 带有子查询的选项(MAXDOP)?

c# - 这段 C# 代码的作用是什么?

java - 如何阻止编译器将未初始化的对象读取为错误

PHP 7.0/Yii 1/MS SQL Server 2008 : PHP is unable to find the driver

json - 使用 null 解码字符串编码的 json int 在 null 时使用以前的值

java - 为什么我的 Spring @Autowired 字段为空?

JavaScript Date.parse() 和空日期

sql-server - SqlHierarchyId.Parse 失败,因为输入字符串 '1.1.3' 不是 SqlHierarchyId 节点的有效字符串表示形式

java - 通过 Windows 身份验证连接到 SQL Server,并使用 Java 提供凭据

sql - 保持多个数据库之间的引用完整性