我正在使用SQL Server 2014
并且我有这个简单的 T-SQL 查询:
USE MyDatabase
SELECT * FROM [t1]
WHERE DATALENGTH([Email]) > 0 OR [Email] <> ' '
我想排除电子邮件字段显示为空白或空的所有记录。
运行上述查询时,它还会提取带有 BLANK(显示为空)和 NULLS 的记录。
我的 FILTER 语法有什么问题?
我正在使用SQL Server 2014
并且我有这个简单的 T-SQL 查询:
USE MyDatabase
SELECT * FROM [t1]
WHERE DATALENGTH([Email]) > 0 OR [Email] <> ' '
我想排除电子邮件字段显示为空白或空的所有记录。
运行上述查询时,它还会提取带有 BLANK(显示为空)和 NULLS 的记录。
我的 FILTER 语法有什么问题?
CREATE TABLE T(
NAME VARCHAR(10),
EMAIL VARCHAR(30)
)
insert into T
SELECT 'A','ab@gmail.com'
insert into T
SELECT 'B',''
insert into T
SELECT 'B',' '
insert into T
SELECT 'B',' '
insert into T
SELECT 'B',NULL
SELECT * FROM t
WHERE LEN(RTRIM(LTRIM(EMAIL)))>0
Seek records where trimming the data still results in some length:
SELECT *
FROM [t1]
WHERE DATALENGTH(RTRIM([Email])) > 0
But actually, tidying the data up would be better than keep catering for junk in the field
UPDATE t1 SET Email = NULLIF(LTRIM(RTRIM(Email)),'')
This way all your emails end up trimmed of spaces or null - all "blanks" become null which means they automatically drop out of queries. It also means the column can be indexed for fast searching and no longer has to be manipulated on every query
你可以去简单的条件。
USE MyDatabase
SELECT * FROM [t1]
WHERE LEN(Email) > 0
更新:简单测试
SELECT * FROM (VALUES ('email'),(null),('')) as t(Val)
where len(val) > 0
瓦尔 |
---|
电子邮件 |