String.IsNullOrEmpty like function for VARCHARs in SQL?

前端 未结 10 2169
一个人的身影
一个人的身影 2021-02-12 11:10

Say I\'ve got a function or stored procedure that takes in several VARCHAR parameters. I\'ve gotten tired of writing SQL like this to test if these parameters have a value:

10条回答
  •  生来不讨喜
    2021-02-12 12:01

    Here is my function that "extends" ISNULL and checks for empty as well. The test value is checked for null and if it is not null it is trimmed and then checked for length.

    The function returns the test string if it is NOT Null or Empty, otherwise the second string is returned.

    CREATE FUNCTION [dbo].[ISNULLOREMPTY]
    (   
        @value NVARCHAR(max),
        @return NVARCHAR(max)
    )
    RETURNS NVARCHAR(MAX)
    AS
    BEGIN 
    
    IF (@value IS NULL)
    BEGIN
        RETURN @return
    END
    ELSE
    BEGIN
        IF (LEN(LTRIM(@value)) = 0)
        BEGIN 
            RETURN @return
        END 
    END
    
    RETURN @value;
    END
    GO
    

提交回复
热议问题