SQL 字符串变量的空或空检查

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16080139/
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 14:53:29  来源:igfitidea点击:

Null or empty check for a string variable

sqlsql-server-2008nullnull-check

提问by Bharath

if((isnull(@value,''))='')

I want to know whether the above piece of code works in checking if the variable is null or empty.

我想知道上面的代码在检查变量是空还是空时是否有效。

回答by Guffa

Yes, that code does exactly that.

是的,该代码正是这样做的。

You can also use:

您还可以使用:

if (@value is null or @value = '')

Edit:

编辑:

With the added information that @valueis an intvalue, you need instead:

使用@value作为int值的附加信息,您需要:

if (@value is null)

An intvalue can never contain the value ''.

一个int值不能包含值''

回答by AnasChavadi

Use This way is Better

使用这种方式更好

if LEN(ISNULL(@Value,''))=0              

This check the field is emptyor NULL

此检查字段是emptyNULL

回答by Tim Schmelter

Yes, you could also use COALESCE(@value,'')=''which is based on the ANSI SQL standard:

是的,您也可以使用COALESCE(@value,'')=''它基于 ANSI SQL 标准:

SELECT CASE WHEN COALESCE(@value,'')='' 
    THEN 'Yes, it is null or empty' ELSE 'No, not null or empty' 
    END AS IsNullOrEmpty

DEMO

演示

回答by bvr

Yes, it works. Check the below example. Assuming @value is not int

是的,它有效。检查下面的例子。假设@value 不是int

WITH CTE 
AS
(
    SELECT NULL AS test
    UNION
    SELECT '' AS test
    UNION
    SELECT '123' AS test
)

SELECT 
    CASE WHEN isnull(test,'')='' THEN 'empty' ELSE test END AS IS_EMPTY 
FROM CTE

Result :

结果 :

IS_EMPTY
--------
empty
empty
123

回答by milan

Try this:

尝试这个:

ISNULL(IIF (ColunmValue!='',ColunmValue, 'no units exists') , 'no units exists') AS 'ColunmValueName' 

回答by Fahad Akbar

You can try

你可以试试

<column_name> is null

in the whereclause.

where条款中。

回答by Ajay Jamwal

You can try this.....

你可以试试这个......

DECLARE @value Varchar(100)=NULL
IF(@value = '' OR @value IS NULL)
  BEGIN
    select 1
  END
ELSE
  BEGIN
    select 0
  END

回答by Sérgio Roberto Penha Heredia

declare @sexo as char(1)

select @sexo='F'

select * from pessoa

where isnull(Sexo,0) =isnull(@Sexo,0)