如何在where子句中使用NULLIF?

问题描述 投票:0回答:6

我想做这样的事情:

select
     col_1, col_2, etc
from
     table
where
     col_1 = nullif('', '')

我做错了吗?我没有得到任何结果。

编辑:

我的预期结果是将每条记录返回到col_1为NULL的位置。

我知道我可以使用col_1为null的地方,但我使用的是SSIS和变量。有时col_1实际上是NULL,有时则不是。

样本数据:

 collaboration     first_name     last_name          city     
          NULL            Bob         Smith       Chicago
Data Migration           John         Smith        Austin
          NULL           Pika           Chu       Houston
    Production            ash       ketchum         tokyo

有时我可能想要返回协作为NULL的记录,有时我想返回记录为Production的记录。

如果可能的话,我想使用相同的查询,几乎没有修改。

编辑第2部分:

我试着试试这个。

select
     col_1, col_2, etc
from
     table
where
     case
         when col_1  = '' then NULL
         else col_1
         end

但我收到错误消息:

An expression of non-boolean type specified in a context where a condition is expected, near ORDER.

查询速度不是我关心的事情。

sql sql-server nullif
6个回答
1
投票

试试这个,它可以处理具有空值或空格的列

SELECT
     col_1, col_2, etc
FROM
     Table
WHERE
     ISNULL(NULLIF(col_1 ,''),'1') = '1'

3
投票

这是您需要的查询

select
     col_1, col_2, etc
from
     table
where
     col_1 is null

is null检查列是否为空,nullif(@expr1,@expr2)可以重写为:

case when @expr1 = @expr2 return null else return @expr1 end

编辑:你可以放松过滤器将OR条件添加到'where'子句中(提示:记得在AND之前评估OR

select
     col_1, col_2, etc
from
     table
where
     (col_1 is null OR col1 like 'production')

如果你想决定你需要的运行时,你可以写一个程序:

create proc my_proc @var AS varchar(100) = 'NULL§159§' -- this defaults to null, if you put a parameter it queries with parameter passed
as
select
         col_1, col_2, etc
    from
         table
    where
         WHERE coalesce(col_1,'NULL§159§') = @var 
-- added §159§ symbol to the null to make sure the queried string is impossible in the database, 
-- obviously into the database the value 'NULL159' hase become a sort of 'reserved word', but hopefully is odd enough not to appear in data
GO

并由exec my_proc('production')称呼它


0
投票

你可以做点什么

select
     col_1, col_2, etc
from
     table
where
     col_1 IS NULL OR col_1 = ''

0
投票
select
     col_1, col_2, etc
from
     table
where
     collaboration IS NULL OR collaboration ='Production'

0
投票

水晶球的时间来自我。这是我对OP想要的猜测:

DECLARE @Prod varchar(15);
--SET @Prod = 'Production';

SELECT {Columns}
FROM YourTable
WHERE Col1 = @Prod
   OR (Col1 IS NULL AND @Prod IS NULL);

0
投票

试试这个。

DECLARE @SearchValue VARCHAR(50)
SELECT col_1, col_2, etc
FROM YourTable
WHERE ISNULL(col_1,'') = ISNULL(@SearchValue,'')
© www.soinside.com 2019 - 2024. All rights reserved.