以下是我的表(TestTable)
,其中Column_3
是NULL
。
Column_1 Column_2 Column_3
-------- -------- --------
1 2 NULL
1 3 NULL
5 6 NULL
根据功能,用户可以选择一个或多个columns
。
例如,如果用户选择Column_3 & Column_2
,其中Column_3
为NULL
。我想告诉用户Column_3
是NULL
。
查询:适用于单列
if exists(select * from TestTable where Column_3 is null)
print 'Yes'
else
print 'No'
结果:
Yes
查询:对于多列(不工作)
declare @columns nvarchar(max), @tableName nvarchar(max), @query nvarchar(max)
set @columns = 'Column_3, Column_2'
set @tableName = 'TestTable'
set @query = 'select * from (select ' + @columns + ' from ' + @tableName + ') as Result'
print @query
EXEC SP_EXECUTESQL @query
这里
@query = select * from (select Column_3, Column_2 from TestTable) as Result
上面的查询给出了这两列的结果。我不确定如何在此查询中检查多个列的NULL
。如果我在最后一个括号之后或之前添加IS NULL
(就像我为单列所做的那样),它会给我Incorrect syntax near the keyword 'is'.
错误。在这种情况下如何实现目标?
答案 0 :(得分:3)
我们可以在IN
的帮助下查看
...WHERE NULL IN (Column_2, Column_3)
来自您的评论Well the multiple column will be Column_3, Column_2 in format
可能这对你有帮助
select * from (select Column_3, Column_2 from @temp where null in (Column_3, Column_2)) as Result
答案 1 :(得分:2)
我稍微修改了您的原始示例,以便提供两种解决方案:
Column_1 Column_2 Column_3
-------- -------- --------
1 2 NULL
1 NULL NULL
5 6 NULL
首先,测试NULL并计算它们:
select
sum(case when Column_1 is null then 1 else 0 end) as Column_1,
sum(case when Column_2 is null then 1 else 0 end) as Column_2,
sum(case when Column_3 is null then 1 else 0 end) as Column_3,
from TestTable
产生一个NULL计数:
Column_1 Column_2 Column_3
0 1 3
如果结果为0,则没有NULL。
第二次,让我们计算非NULL:
select
sum(case when Column_1 is null then 0 else 1 end) as Column_1,
sum(case when Column_2 is null then 0 else 1 end) as Column_2,
sum(case when Column_3 is null then 0 else 1 end) as Column_3,
from TestTable
...但是因为我们在这里计算非NULL,所以可以简化为:
select
count(Column_1) as Column_1,
count(Column_2) as Column_2,
count(Column_3) as Column_3,
from TestTable
任何一个产生:
Column_1 Column_2 Column_3
3 2 0
如果结果为0,则列完全由NULL组成。
如果你只需要检查一个给定的列,那么TOP 1会更快,因为它应该在第一次击中时停止:
select count(*) from (select top 1 'There is at least one NULL' AS note from TestTable where Column_3 is NULL) a
0 =没有NULL,1 =至少有一个NULL
SELECT COUNT(*) FROM (SELECT TOP 1 'There is at least one non-NULL' AS note FROM sat_data_active_season_group WHERE season_group IS NOT NULL) a
0 =它们都是NULL,1 =至少有一个非NULL
我希望这会有所帮助。
答案 2 :(得分:1)
请尝试以下操作。
您可以使用CASE找到null able列。
Select CASE WHEN Column_3 IS NULL THEN 'Column 3 is null' ELSE Column_3 END as Column3,
CASE WHEN Column_2 IS NULL THEN 'Column 2 is null' ELSE Column_2 END as Column2
From TableName
答案 3 :(得分:0)
听起来你需要CASE
声明。 Reference
示例:
SELECT CASE
WHEN ISNULL(Column_3) THEN -- do something
WHEN NOT ISNULL(Column_3) THEN -- do something else
AS Column_3 -- or some other name