如何将cte值赋给变量

时间:2014-11-13 11:48:55

标签: sql-server-2008

;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中的值设置为变量

4 个答案:

答案 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在单个SELECTINSERTUPDATEDELETE语句的执行范围内定义。 (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