;with CTEima(PersonId,IsEmployeeActive)
as
(select count(*)
from custom.viwSSAppsEmpMasterExtended vem
where vem.SupervisorPersonId = @p_PersonId
union all
select CTEima.IsEmployeeActive
from Custom.viwSSAppsEmpMasterExtended vem
join CTEima on CTEima.PersonId = vem.SupervisorPersonId
)
set @v_IsManager = (select count(*)from CTEima where IsEmployeeActive = 'Y')
这里我得到的错误就像 关键字'set'
附近的语法不正确告诉我如何将CTE中的值设置为变量
答案 0 :(得分:11)
您无法在SET
语句中使用SELECT
关键字设置值。
您可以将查询中的字段分配给SELECT
语句中的变量:
WITH CTE AS (
/** .. Your Query Here .. **/
)
SELECT
@YourVariable = FieldNameOrSubquery -- In short: Expression
FROM
CTE
在这种情况下,SELECT列表中的所有文件都应该分配给变量!
或者您可以通过SELECT
关键字将单行 - 单列 SET
语句的结果分配给变量:
SET @YourVariable = (SELECT COUNT(1) FROM YourTable).
您无法混合上述选项。
此外,CTE在单个SELECT
,INSERT
,UPDATE
或DELETE
语句的执行范围内定义。 (http://msdn.microsoft.com/en-us/library/ms175972.aspx)。 SET
不是SELECT
/ INSERT
/ UPDATE
/ DELETE
语句,这就是SQL Server报告语法错误的原因(CTE无法在SET语句的范围。)
您的示例查询解决方案
;WITH CTEima(PersonId,IsEmployeeActive) AS
( SELECT COUNT(*)
FROM custom.viwSSAppsEmpMasterExtended vem
WHERE vem.SupervisorPersonId = @p_PersonId
UNION ALL
SELECT CTEima.IsEmployeeActive
FROM Custom.viwSSAppsEmpMasterExtended vem
JOIN CTEima on CTEima.PersonId = vem.SupervisorPersonId
)
SELECT @v_IsManager = COUNT(*)
FROM CTEima
WHERE IsEmployeeActive = 'Y'
答案 1 :(得分:1)
用这个替换你的最后一行:
select @v_IsManager = count(*) from CTEima where IsEmployeeActive = 'Y'
答案 2 :(得分:0)
;with CTEima(PersonId,IsEmployeeActive)
as
(select count(*)
from custom.viwSSAppsEmpMasterExtended vem
where vem.SupervisorPersonId = @p_PersonId
union all
select CTEima.IsEmployeeActive
from Custom.viwSSAppsEmpMasterExtended vem
join CTEima on CTEima.PersonId = vem.SupervisorPersonId
)
select @v_IsManager = count(*) from CTEima where IsEmployeeActive = 'Y'
答案 3 :(得分:0)
DECLARE @a int SET @A = 1234 ; 与CTE AS(选择 COL1, COL2 来自xyz
在哪里Col1 = @A), DT AS(选择 @A Col1)
选择 * 从dt d LEFT JOIN CTE vd ON vd.col1 = d.col1