How to use NULL or empty string in SQL

2019-02-01 15:20发布

I would like to know how to use NULL and an empty string at the same time in a WHERE clause in SQL Server. I need to find records that have either null values or an empty string. Thanks.

15条回答
你好瞎i
2楼-- · 2019-02-01 15:48

In sproc, you can use the following condition:

DECLARE @USER_ID VARCAHR(15)=NULL --THIS VALUE IS NULL OR EMPTY DON'T MATTER
IF(COALESCE(@USER_ID,'')='')
PRINT 'HUSSAM'
查看更多
唯我独甜
3楼-- · 2019-02-01 15:48

youe check null With IS NULL and string Empty With LEN(RTRIM(LTRIM(Column))) = 0 in

SELECT *
FROM AppInfra.Person
WHERE   LEN(RTRIM(LTRIM(NationalCode))) = 0 OR  NationalCode IS NULL
查看更多
戒情不戒烟
4楼-- · 2019-02-01 15:49

If you need it in SELECT section can use like this.

    SELECT  ct.ID, 
            ISNULL(NULLIF(ct.LaunchDate, ''), null) [LaunchDate]
    FROM    [dbo].[CustomerTable] ct

you can replace the null with your substitution value.

查看更多
孤傲高冷的网名
5楼-- · 2019-02-01 15:49

This is ugly MSSQL:

CASE WHEN LTRIM(RTRIM(ISNULL([Address1], ''))) <> '' THEN [Address2] ELSE '' END
查看更多
霸刀☆藐视天下
6楼-- · 2019-02-01 15:50

my best solution :

WHERE  
    COALESCE(char_length(fieldValue), 0) = 0

COALESCE returns the first non-null expr in the expression list().

if the fieldValue is null or empty string then: we will return the second element then 0.

so 0 is equal to 0 then this fieldValue is null or empty string.

in python for exemple:

def coalesce(fieldValue):
    if fieldValue in (null,''):
        return 0

good luck

查看更多
Explosion°爆炸
7楼-- · 2019-02-01 15:53

To find rows where col is NULL, empty string or whitespace (spaces, tabs):

SELECT *
FROM table
WHERE ISNULL(LTRIM(RTRIM(col)),'')=''

To find rows where col is NOT NULL, empty string or whitespace (spaces, tabs):

SELECT *
FROM table
WHERE ISNULL(LTRIM(RTRIM(col)),'')<>''
查看更多
登录 后发表回答