How do check if a parameter is empty or null in Sql Server stored procedure in IF statement?

半腔热情 提交于 2019-12-20 17:32:15

问题


I read this: How do I check if a Sql server string is null or empty but it not helped me in this situation.

The piece of code from my stored procedure:

IF (@item1 IS NOT NULL) OR (LEN(@item1) > 0)
        SELECT @sql = 'SELECT * FROM TEST1'
    ELSE
        SELECT @sql = 'SELECT * FROM TEST2'
 PRINT @sql;

@item1 is NVARCHAR(1000) type.

When execute this stored procedure, I provided the value for item1

EXEC    [dbo].[my_proc]
        @item1 = N''

it shows

SELECT * FROM TEST1 // it is correct if @item1 = N'some'

instead of

SELECT * FROM TEST2

It is somewhere a function in sql to verify if a string is null or empty OR I made somewhere a mistake ?

Like in C# -> string.IsNullOrEmpty(myValue)


回答1:


that is the right behavior.

if you set @item1 to a value the below expression will be true

IF (@item1 IS NOT NULL) OR (LEN(@item1) > 0)

Anyway in SQL Server there is not a such function but you can create your own:

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



回答2:


To check if variable is null or empty use this:

IF LEN(ISNULL(@var, '')) = 0
    -- Is empty or NULL
ELSE
    -- Is not empty and is not NULL



回答3:


Of course that works; when @item1 = N'', it IS NOT NULL.

You can define @item1 as NULL by default at the top of your stored procedure, and then not pass in a parameter.



来源:https://stackoverflow.com/questions/12264602/how-do-check-if-a-parameter-is-empty-or-null-in-sql-server-stored-procedure-in-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!