0

I have tried the queries below to check whether the current year is Leap-Year or not.

Declare @leapyearstrt int = 0

--1st query
select @leapyearstrt = ISNULL(ISLEAPYEAR,0)
                       FROM [dbo].[TimeElement] 
                       WHERE CurrentDate = getdate()

--2nd query
SET @leapyearstrt  = (SELECT isnull(ISLEAPYEAR,0) 
                       FROM [dbo].[TimeElement] 
                       WHERE CurrentDate = getdate()
                       )

If the data does not exist in the table for the given date, 1st query returns @leapyearstrt as 0, but 2nd query returns @leapyearstrt as NULL.

Why does it happen? How to assign the 0 value in the SET statement if data does not exist in the table?

(P.S : I have used SET to assign the value because select may return more than one row)

Vladimir Baranov
  • 31,799
  • 5
  • 53
  • 90
bmsqldev
  • 2,627
  • 10
  • 31
  • 65
  • If there is no value then Parameter have to return the default value assign to it . is it? – bmsqldev Dec 03 '15 at 07:56
  • Possible duplicate of [SET versus SELECT when assigning variables?](http://stackoverflow.com/questions/3945361/set-versus-select-when-assigning-variables) – Lukasz Szozda Dec 03 '15 at 08:00

2 Answers2

1

First of all, if SELECT returns more than 1 row, then SET (your second query) fails:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

But, variable assignment within SELECT (your first query) works. It is not defined which row will be used to assign the final value, though.


If you want to use SET, then make sure that SELECT returns at most 1 row:

SET @leapyearstrt  = (SELECT TOP(1) isnull(ISLEAPYEAR,0) 
                       FROM [dbo].[TimeElement] 
                       WHERE CurrentDate = getdate()
        -- ideally you should add a proper ORDER BY to pick the row that you need
                       );

And then add this line of code to cover the case when SELECT returns 0 rows.

SET @leapyearstrt = ISNULL(@leapyearstrt, 0);
Vladimir Baranov
  • 31,799
  • 5
  • 53
  • 90
0

You can use ISNULL function, assuming the subquery is returning one row:

SET @leapyearend  = ISNULL((SELECT TOP 1 ISLEAPYEAR 
                            FROM [dbo].[TimeElement] 
                            WHERE CurrentDate = getdate()
                           ), 0)

The difference between those two is that in the first query if row is not found the assignment is not executed at all. In second version it is executed wether row is found or not.

Giorgi Nakeuri
  • 35,155
  • 8
  • 47
  • 75