如何在 SQL Server 中检查一个 WHERE
条件中的列是否不为空并且不是空字符串 (''
)?
如何在 SQL Server 中检查一个 WHERE
条件中的列是否不为空并且不是空字符串 (''
)?
如果您只想匹配 "" 作为空字符串
WHERE DATALENGTH(COLUMN) > 0
WHERE COLUMN <> ''
当在 WHERE
子句中使用时,这两者都不会返回 NULL
值。因为对于这些情况,NULL
会被评估为 UNKNOWN
而不是 TRUE
。
CREATE TABLE T
(
C VARCHAR(10)
);
INSERT INTO T
VALUES ('A'),
(''),
(' '),
(NULL);
SELECT *
FROM T
WHERE C <> ''
A
。也就是说,此查询将排除值为 NULL
、空字符串或完全由空格组成的字符串的行。
WHERE NULLIF(your_column, '') IS NOT NULL
现在(已经过去4.5年),为了方便人类阅读,我会直接使用:
WHERE your_column <> ''
虽然有一种诱惑让空值检查变得显式...
WHERE your_column <> ''
AND your_column IS NOT NULL
...正如@Martin Smith在被接受的答案中所证明的那样,它并没有真正增加任何内容(而我个人现在完全避免使用SQL nulls,所以它对我也不适用!)。
基本方式
SELECT *
FROM [TableName]
WHERE column_name!='' AND column_name IS NOT NULL
您可以使用其中任何一个来检查null、空格和空字符串。
WHERE COLUMN <> ''
WHERE LEN(COLUMN) > 0
WHERE NULLIF(LTRIM(RTRIM(COLUMN)), '') IS NOT NULL
Coalesce将null折叠成默认值:
COALESCE (fieldName, '') <> ''
where (field is not null and field <> '')
如果行数不多或该字段没有索引,您可以使用:
where isnull(field,'') <> ''
请检查:where value > '' -- 不为空且不为null
-- 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
检查这种方式 其中Ph!= ''且Ph ='123456780'
--Check the length of your NULL values
SELECT DATALENGTH(COLUMN) as length_column
FROM your_table
--Filter the length of your NULL values (8 is used as example)
WHERE DATALENGTH(COLUMN) > 8
NULL
单词的 NVARCHAR
数据类型的字符串,而不是实际的 NULL
。要查找这些字符串,您只需要使用 = N'NULL'
,因为它们就像普通字符串一样! - Martin SmithSELECT * FROM [Employee]
WHERE
EMail is not null -- not null check
and Email != '' -- not empty check
WHERE COALESCE(column, '') <> ''
? - Lieven Keersmaekers< ''
和> ''
- 但是,除非有大量带有空字符串值的行,否则可能帮助不大。 - Martin Smith<> ''
and!=''
are both used to check for inequality in SQL queries. However, there is no performance difference between the two. They are essentially equivalent and will produce the same results. It is simply a matter of personal preference or coding style. - undefined