String.IsNullOrEmpty like function for VARCHARs in SQL?

前端 未结 10 1893
一个人的身影
一个人的身影 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:02

    You can do ISNULL(@SomeVarcharParam, '') <> '' or you can create a UDF that returns a bit:

    create function dbo.IsNullOrEmpty(@x varchar(max)) returns bit as
    BEGIN
    IF @SomeVarcharParm IS NOT NULL AND LEN(@SomeVarcharParm) > 0
        RETURN 0
    ELSE
        RETURN 1
    END
    

    And call that using IF NOT dbo.IsNullOrEmpty(@SomeVarcharParam) BEGIN ...

    Keep in mind that when calling a UDF, you MUST prefix the owner of it (here, dbo.)

    0 讨论(0)
  • 2021-02-12 12:03

    Use this function (based on Derek's):

    CREATE FUNCTION dbo.isNullOrEmpty(@x varchar(max)) RETURNS BIT AS
    BEGIN
        IF @x IS NOT NULL AND LEN(@x) > 0
            RETURN 0
    
        RETURN 1
    END
    

    as

    dbo.isNullOrEmpty(@someVar)
    

    or

    WHERE dbo.isNullOrEmpty(@someVar) = 1
    

    in a stored procedure or query.

    0 讨论(0)
  • 2021-02-12 12:12

    You can just do IF @SomeVarcharParam <> '' since the condition will evaluate to NULL and the branch won't be taken if the parameter is null

    0 讨论(0)
  • 2021-02-12 12:13
    IF COALESCE(@SomeVarcharParm, '') <> ''
    BEGIN
       -- do stuff
    END
    
    0 讨论(0)
提交回复
热议问题