我们如何在SQL Server WHERE条件下检查列是否不为空,而不是空字符串(“)?
当前回答
只要检查:where值> "——不为空,不为空
-- COLUMN CONTAINS A VALUE (ie string not null and not empty) :
-- (note: "<>" gives a different result than ">")
select iif(null > '', 'true', 'false'); -- false (null)
select iif('' > '', 'true', 'false'); -- false (empty string)
select iif(' ' > '', 'true', 'false'); -- false (space)
select iif(' ' > '', 'true', 'false'); -- false (tab)
select iif('
' > '', 'true', 'false'); -- false (newline)
select iif('xxx' > '', 'true', 'false'); -- true
--
--
-- NOTE - test that tab and newline is processed as expected:
select 'x x' -- tab
select 'x
x' -- newline
其他回答
Coalesce将把null值折叠成默认值:
COALESCE (fieldName, '') <> ''
WHERE NULLIF(your_column, '') IS NOT NULL
如今(4.5年过去了),为了让人类更容易阅读,我只会使用它
WHERE your_column <> ''
虽然有一种将null检查显式化的诱惑……
WHERE your_column <> ''
AND your_column IS NOT NULL
...正如@Martin Smith在接受的答案中所演示的那样,它实际上没有添加任何东西(而且我个人现在完全避免使用SQL空,所以它对我不适用!)
只要检查:where值> "——不为空,不为空
-- COLUMN CONTAINS A VALUE (ie string not null and not empty) :
-- (note: "<>" gives a different result than ">")
select iif(null > '', 'true', 'false'); -- false (null)
select iif('' > '', 'true', 'false'); -- false (empty string)
select iif(' ' > '', 'true', 'false'); -- false (space)
select iif(' ' > '', 'true', 'false'); -- false (tab)
select iif('
' > '', 'true', 'false'); -- false (newline)
select iif('xxx' > '', 'true', 'false'); -- true
--
--
-- NOTE - test that tab and newline is processed as expected:
select 'x x' -- tab
select 'x
x' -- newline
以基本的方式
SELECT *
FROM [TableName]
WHERE column_name!='' AND column_name IS NOT NULL
一种索引友好的方法是:
where (field is not null and field <> '')
如果没有很多行或者这个字段没有索引,你可以使用:
where isnull(field,'') <> ''