Check if a parameter is null or empty in a stored procedure

前端 未结 12 1039
轮回少年
轮回少年 2020-12-02 22:09

I know how to check if a parameter is null but i am not sure how to check if its empty ... I have these parameters and I want to check the previous parameters are empty or n

相关标签:
12条回答
  • 2020-12-02 22:54

    I sometimes use NULLIF like so...

    IF NULLIF(@PreviousStartDate, '') IS NULL
    

    There's probably no reason it's better than the way suggested by @Oded and @bluefeet, just stylistic preference.

    @danihp's method is really cool but my tired old brain wouldn't go to COALESCE when I'm thinking is null or empty :-)

    0 讨论(0)
  • 2020-12-02 22:54

    To check if variable is null or empty use this:

    IF LEN(ISNULL(@var, '')) = 0
    
    0 讨论(0)
  • 2020-12-02 22:58

    I use coalesce:

    IF ( COALESCE( @PreviousStartDate, '' ) = '' ) ...
    
    0 讨论(0)
  • 2020-12-02 22:58

    What about combining coalesce and nullif?

    SET @PreviousStartDate = coalesce(nullif(@PreviousStartDate, ''), '01/01/2010')
    
    0 讨论(0)
  • 2020-12-02 22:59

    you can use:

    IF(@PreviousStartDate IS NULL OR @PreviousStartDate = '')
    
    0 讨论(0)
  • 2020-12-02 23:00

    If you want to use a parameter is Optional so use it.

    CREATE PROCEDURE uspGetAddress @City nvarchar(30) = NULL, @AddressLine1 nvarchar(60) = NULL
        AS
        SELECT *
        FROM AdventureWorks.Person.Address
        WHERE City = ISNULL(@City,City)
        AND AddressLine1 LIKE '%' + ISNULL(@AddressLine1 ,AddressLine1) + '%'
        GO
    
    0 讨论(0)
提交回复
热议问题