Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign INT Variable From Select Statement in SQL

Tags:

sql

database

tsql

Why do I get a syntax error on the following SQL statements:

DECLARE @Count90Day int;

SET @Count90Day =  SELECT COUNT(*) FROM Employee WHERE DateAdd(day,30,StartDate) BETWEEN
DATEADD(day,-10,GETDATE()) AND DATEADD(day,10,GETDATE())  AND Active ='Y' 

I am trying to assign the number of rows returned from my Select statement to the variable @Count90Day.

like image 550
Bill Greer Avatar asked Sep 03 '13 11:09

Bill Greer


3 Answers

You need parentheses around the subquery:

DECLARE @Count90Day int;

SET @Count90Day =  (SELECT COUNT(*)
                    FROM Employee
                    WHERE DateAdd(day,30,StartDate) BETWEEN DATEADD(day,-10,GETDATE()) AND 
                                                            DATEADD(day,10,GETDATE())  AND
                          Active ='Y'
                   );

You can also write this without the set as:

DECLARE @Count90Day int;

SELECT @Count90Day =  COUNT(*)
FROM Employee
WHERE DateAdd(day,30,StartDate) BETWEEN DATEADD(day,-10,GETDATE()) AND DATEADD(day,10,GETDATE()) AND
      Active ='Y';
like image 109
Gordon Linoff Avatar answered Oct 10 '22 06:10

Gordon Linoff


You can assign it within the SELECT, like so:

DECLARE @Count90Day int;

SELECT @Count90Day = COUNT(*) 
FROM Employee 
WHERE DateAdd(day,30,StartDate) BETWEEN
DATEADD(day,-10,GETDATE()) AND DATEADD(day,10,GETDATE())  AND Active ='Y' 
like image 42
StuartLC Avatar answered Oct 10 '22 07:10

StuartLC


You don't assign SQL variables in a SELECT like that, you can do:

SELECT @Count90Day = COUNT(*) 
FROM Employee WHERE DateAdd(day,30,StartDate) BETWEEN
DATEADD(day,-10,GETDATE()) AND DATEADD(day,10,GETDATE())  AND Active ='Y' 
like image 35
Darren Avatar answered Oct 10 '22 06:10

Darren