Tsql 对于alternate,带空字符串的ISNULL仍然返回一些null
我在select语句中将此字段作为其中一个字段:Tsql 对于alternate,带空字符串的ISNULL仍然返回一些null,tsql,Tsql,我在select语句中将此字段作为其中一个字段: select ...some fields (select ISNULL( TagNames, '') from TagNames_CTE as tagNames where Content.ID = tagNames.EntryID) as tags from SomeTable 我注意到,即使当我使用ISNULL并告诉它用空字符串替换这些值时,对于一些记录,我仍然会返回NULL
select
...some fields
(select ISNULL( TagNames, '') from TagNames_CTE as tagNames
where Content.ID = tagNames.EntryID) as tags
from SomeTable
我注意到,即使当我使用ISNULL并告诉它用空字符串替换这些值时,对于一些记录,我仍然会返回NULL。它没有用空字符串替换它们,我不明白为什么。我想您会发现,在没有找到行的情况下,subselect实际上返回NULL 如果在
TagNames\u CTE
中找到一行,where
子句触发且TagNames
为空,则函数会将该行转换为'
但如果根本找不到行,则不会调用该函数(因为没有行可以让它发挥作用),并且整个子选择的结果为空,因为它必须在该列中为外部选择返回某些内容
一种简单的检查方法是单独运行子查询(不带ISNULL()
),查看它是否返回包含NULL
的行,或者根本不返回行-尝试以下简单查询:
select 1,
(select isnull (null,2) from dummytable where 1 = 0)
from dummytable
以及:
你可能会发现前者给你1,null
,而后者给你1,2
。用下面的语句在MySQL中进行了测试,您可以看到这很可能是正确的
> create table xyzzy (plugh integer);
> insert into xyzzy values (42):
> select 1,(select ifnull (null, 2) from xyzzy where 1 = 0) from xyzzy;
1 NULL
> select 1,(select ifnull (null, 2) from xyzzy where 1 = 1) from xyzzy;
1 2
因为在子查询中,
ISNULL
只能影响实际存在于行中的NULL
。我假设您实际需要处理的是子查询不返回任何行的情况:
select
...some fields
ISNULL((select TagNames from TagNames_CTE as tagNames
where Content.ID = tagNames.EntryID), '') as tags
from SomeTable
因此,将其移动到子查询的外部。(我通常也会推荐
COALESCE
而不是ISNULL
。它是标准的SQL,支持多个参数,类型强制很有意义)hmmm有人会认为这会冒泡,最后一个ISNULL会把它当作一个包罗万象的东西来处理?@Coffee,不,我不这么认为,在低于实际选择的一个级别上为空。
select
...some fields
ISNULL((select TagNames from TagNames_CTE as tagNames
where Content.ID = tagNames.EntryID), '') as tags
from SomeTable