SQL 存储过程变量空检查

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13512636/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 12:16:15  来源:igfitidea点击:

SQL stored procedure variable null checking

sqlstored-procedures

提问by Arvind

Below is part of a stored procedure that I have, it would be of great help if you can point me why is that even when @DefaultIDis null after executing the select statement it does not enter the if condition, is there are different method I have to follow to assign the value to @DefaultIDfor it to be available for null checking.

下面是我拥有的存储过程的一部分,如果您能指出我为什么即使@DefaultID在执行 select 语句后为 null 它也不会进入 if 条件,这将是非常有帮助的,是否有不同的方法我必须按照将值分配给@DefaultID它以使其可用于空值检查。

Thank you in advance.

先感谢您。

DECLARE @DefaultID varchar(25)
DECLARE @ISDefault varchar(1)

SELECT @DefaultID = (SELECT TABLE1.DEFID as DEFID
                     FROM TABLE1
                     WHERE TABLE1.ID = '123')

IF (@DefaultID = '')
    SET @ISDefault = '1'
ELSE
    SET @ISDefault = '0'

回答by Mahmoud Gamal

Use

IF @DefaultID IS NULL

Instead of IF @DefaultID =''

代替 IF @DefaultID =''

NULLand ''are two different things.

NULL并且''是两种不同的东西。

回答by TechDo

Please check using

请检查使用

IF ISNULL(@DefaultID, '') = ''instead of IF(@DefaultID = '')

IF ISNULL(@DefaultID, '') = ''代替 IF(@DefaultID = '')

I guess you are using MS Sql server.

我猜你正在使用 MS Sql 服务器。

回答by Pranav

simply use this :-

只需使用这个:-

  IF(@DefaultID is NULL)

回答by AnandPhadke

IF(len(@DefaultID) > 0)
 SET @ISDefault = '1'
ELSE
    SET @ISDefault = '0'