为什么我在以下SQL语句中出现语法错误:
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'
我正在尝试将从Select语句返回的行数分配给变量@ Count90Day。
答案 0 :(得分:16)
子查询周围需要括号:
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'
);
您也可以在没有set
的情况下将其写为:
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';
答案 1 :(得分:2)
您可以在SELECT
内分配,如下所示:
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'
答案 2 :(得分:1)
你不能像SELECT
这样分配SQL变量,你可以这样做:
SELECT @Count90Day = COUNT(*)
FROM Employee WHERE DateAdd(day,30,StartDate) BETWEEN
DATEADD(day,-10,GETDATE()) AND DATEADD(day,10,GETDATE()) AND Active ='Y'
答案 3 :(得分:1)
这应该有效
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'
答案 4 :(得分:0)
您可以在DECLARE
语句中指定变量,只需在请求周围使用圆括号。
DECLARE @Count90Day as int = (SELECT COUNT(*)
FROM Employee
WHERE DateAdd(day,30,StartDate) BETWEEN
DATEADD(day,-10,GETDATE()) AND
DATEADD(day,10,GETDATE())
AND Active ='Y')