如何在 IF 语句中检查 Sql Server 存储过程中的参数是否为空或空? [英] How do check if a parameter is empty or null in Sql Server stored procedure in IF statement?
问题描述
我读了这个:如何检查 Sql 服务器字符串是否为 null 或为空 但在这种情况下它对我没有帮助.
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
是 NVARCHAR(1000)
类型.
当执行这个存储过程时,我提供了item1
When execute this stored procedure, I provided the value for item1
EXEC [dbo].[my_proc]
@item1 = N''
显示
SELECT * FROM TEST1
//如果@item1 = N'some'
代替
SELECT * FROM TEST2
它是 sql 中的某个函数来验证字符串是 null 还是空 OR 我在某个地方犯了错误?
It is somewhere a function in sql to verify if a string is null or empty OR I made somewhere a mistake ?
就像在 C# 中一样 -> string.IsNullOrEmpty(myValue)
Like in C# -> string.IsNullOrEmpty(myValue)
推荐答案
这是正确的行为.
如果您将@item1
设置为一个值,则以下表达式将为真
if you set @item1
to a value the below expression will be true
IF (@item1 IS NOT NULL) OR (LEN(@item1) > 0)
无论如何在 SQL Server 中没有这样的功能,但您可以创建自己的功能:
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
这篇关于如何在 IF 语句中检查 Sql Server 存储过程中的参数是否为空或空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!