Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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)

like image 484
Snake Eyes Avatar asked Sep 04 '12 13:09

Snake Eyes


People also ask

How do you check if a parameter is empty or NULL in SQL Server?

Inside the stored procedure, the parameter value is first tested for Null using the ISNULL function and then checked whether it is Blank (Empty). If the parameter has value then only matching records will be returned, while if the parameter is Null or Blank (Empty) then all records from the table will be returned.

How do you check if a value is NULL or blank in SQL?

SELECT * FROM yourTableName WHERE yourSpecificColumnName IS NULL OR yourSpecificColumnName = ' '; The IS NULL constraint can be used whenever the column is empty and the symbol ( ' ') is used when there is empty value.

Is NULL or empty in SQL Server?

NULL is used in SQL to indicate that a value doesn't exist in the database. It's not to be confused with an empty string or a zero value. While NULL indicates the absence of a value, the empty string and zero both represent actual values.


1 Answers

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 
like image 102
Massimiliano Peluso Avatar answered Oct 08 '22 20:10

Massimiliano Peluso