How to use NULL or empty string in SQL

前端 未结 16 1460
悲&欢浪女
悲&欢浪女 2020-12-23 20: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 o

相关标签:
16条回答
  • 2020-12-23 20:43
    SELECT *
    FROM   Table
    WHERE  column like '' or column IS NULL OR LEN(column) = 0
    
    0 讨论(0)
  • 2020-12-23 20:45

    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)),'')<>''
    
    0 讨论(0)
  • 2020-12-23 20:46

    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.

    0 讨论(0)
  • 2020-12-23 20:46

    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 a null or empty string.

    in python for exemple:

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

    good luck

    0 讨论(0)
  • 2020-12-23 20:46

    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'
    
    0 讨论(0)
  • 2020-12-23 20:47

    Some sargable methods...

    SELECT *
    FROM #T
    WHERE SomeCol = '' OR SomeCol IS NULL;
    
    SELECT *
    FROM #T
    WHERE SomeCol = '' 
    UNION ALL
    SELECT *
    FROM #T
    WHERE  SomeCol IS NULL;
    
    SELECT *
    FROM #T
    WHERE EXISTS ((SELECT NULL UNION SELECT '') INTERSECT SELECT SomeCol);
    

    And some non-sargable ones...

    SELECT *
    FROM #T
    WHERE IIF(SomeCol <> '',0,1) = 1;
    
    SELECT *
    FROM #T
    WHERE NULLIF(SomeCol,'') IS NULL;
    
    SELECT *
    FROM #T
    WHERE ISNULL(SomeCol,'') = '';
    
    0 讨论(0)
提交回复
热议问题