Set Value to a variable – ISNULL or EMPTY

Here is the sql script to set value to a variable, when the value of the variable is NULL or ” (empty).


--Declare a @date variable with default value of NULL

DECLARE @date DATE = NULL

--Set yesterday date if the @date variable value is NULL
SET @date = ISNULL(NULLIF(@date, ''), GETDATE() - 1)
PRINT @date

--Set @date variable value as '' (empty)

SET @date = ''

--Set yesterday date if the @date variable value is NULL
SET @date = ISNULL(NULLIF(@date, ''), GETDATE() - 1)
PRINT @date

--Set @date variable value as a specified date

SET @date = '20160927'

--Set yesterday date if the @date variable value is NULL

--This will not set yesterday value to @date variable, instead it will take the above set value
SET @date = ISNULL(NULLIF(@date, ''), GETDATE() - 1)
PRINT @date

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s