How to use NULL or empty string in SQL

前端 未结 16 1459
悲&欢浪女
悲&欢浪女 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:27
    SELECT * FROM DBO.AGENDA
    WHERE 
      --IF @DT_START IS NULL OR EMPTY
      ( ISNULL( @DT_START,'' ) = '' AND DT_START IS NOT NULL ) -- GET ALL DATE
      OR --ELSE
      ( DT_START >= @DT_START ) --FILTER
    
    -- MORE FILTER
    
    SELECT * FROM DBO.AGENDA
    WHERE 
      ( ( ISNULL( @DT_START,'' ) = '' AND DT_START IS NOT NULL ) OR ( DT_START >= @DT_START ) ) 
      AND
      DT_END < GETDATE()
    
    0 讨论(0)
  • 2020-12-23 20:29

    This is ugly MSSQL:

    CASE WHEN LTRIM(RTRIM(ISNULL([Address1], ''))) <> '' THEN [Address2] ELSE '' END
    
    0 讨论(0)
  • 2020-12-23 20:31

    by this function:

    ALTER FUNCTION [dbo].[isnull](@input nvarchar(50),@ret int = 0)
    RETURNS int
    AS
    BEGIN
    
        return (case when @input='' then @ret when @input is null then @ret else @input end)
    
    END
    

    and use this:

    dbo.isnull(value,0)

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

    You could use isnull function to get both null and empty values of a text field:

    SELECT * FROM myTable
    WHERE isnull(my_nullable_text_field,'') = ''
    
    0 讨论(0)
  • 2020-12-23 20:41
    Select *
    From Table
    Where (col is null or col = '')
    

    Or

    Select *
    From Table
    Where IsNull(col, '') = ''
    
    0 讨论(0)
  • 2020-12-23 20:42
    --setup
    IF OBJECT_ID('tempdb..#T') IS NOT NULL DROP TABLE #T;
    CREATE TABLE #T(ID INT NOT NULL IDENTITY(1,1) PRIMARY KEY, NAME VARCHAR(10))
    INSERT INTO #T (Name) VALUES('JOHN'),(''),(NULL);
    SELECT * FROM #T
     1  JOHN
     2  -- is empty string
     3  NULL
    

    You can examine '' as NULL by converting it to NULL using NULLIF

    --here you set '' to null
    UPDATE #T SET NAME = NULLIF(NAME,'')
    SELECT * FROM #T 
     1  JOHN
     2  NULL
     3  NULL
    

    or you can examine NULL as '' using SELECT ISNULL(NULL,'')

    -- here you set NULL to ''
    UPDATE #T SET NAME = ISNULL(NULL,'') WHERE NAME IS NULL
    SELECT * FROM #T
    1   JOHN
    2   -- is empty string
    3   -- is empty string
    
    --clean up
    DROP TABLE #T
    
    0 讨论(0)
提交回复
热议问题