You can not set values with the SET
keyword in the SELECT
statement.
You could either assign the fields from the query to variables in the SELECT
statement:
WITH CTE AS (
/** .. Your Query Here .. **/
)
SELECT
@YourVariable = FieldNameOrSubquery -- In short: Expression
FROM
CTE
In this case all fileds in the SELECT list should be assigned to a variable!
Or you can assign a single row-single column SELECT
statement's result to a variable by the SET
keyword:
SET @YourVariable = (SELECT COUNT(1) FROM YourTable).
You can not mix the above options.
Furthermore, CTE is defined within the execution scope of a single SELECT
, INSERT
, UPDATE
, or DELETE
statement. (http://msdn.microsoft.com/en-us/library/ms175972.aspx). SET
is not a SELECT
/INSERT
/UPDATE
/DELETE
statement, this is why SQL Server reports a syntax error (CTEs can not be defined in the scope of the SET statement.)
The solution with your example query
;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'
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…