etr*_*pja 1 sql sql-server common-table-expression
我有一个写递归SQL查询,返回一些int值.SQL查询如下所示:
;WITH GroupHIERARCHY(ID)
AS ( SELECT ID
FROM tFirstTable te
WHERE te.LevelID <> 0
AND GroupID =-1
UNION ALL
SELECT t.ElementID
FROM tFirstTable AS t, tSecondTable,GroupHIERARCHY
WHERE t.TypeID=tSecondTable.TypeID
AND GroupHIERARCHY.ID= t.GroupID)
SELECT ID FROM GroupHIERARCHY
Run Code Online (Sandbox Code Playgroud)
这将返回一些整数值.(工作正常)我想要做的是我想写一个如下的查询:
Select * from tExampleTable
WHERE FirstParameter IN (IntegerValuesHere) OR SecondParameter IN (IntegerValuesHere)
Run Code Online (Sandbox Code Playgroud)
其中,IntegerValuesHere是我从递归查询中获得的值.
查询现在看起来像:
Select * FROM tExampleTable
WHERE FirstParameter IN (
;WITH GroupHIERARCHY(ID)
AS ( SELECT ID
FROM tFirstTable te
WHERE te.LevelID <> 0
AND GroupID =-1
UNION ALL
SELECT t.ElementID
FROM tFirstTable AS t, tSecondTable,GroupHIERARCHY
WHERE t.TypeID=tSecondTable.TypeID
AND GroupHIERARCHY.ID= t.GroupID)
SELECT ID FROM GroupHIERARCHY
)
OR SecondParameter IN (
;WITH GroupHIERARCHY(ID)
AS ( SELECT ID
FROM tFirstTable te
WHERE te.LevelID <> 0
AND GroupID =-1
UNION ALL
SELECT t.ElementID
FROM tFirstTable AS t, tSecondTable,GroupHIERARCHY
WHERE t.TypeID=tSecondTable.TypeID
AND GroupHIERARCHY.ID= t.GroupID)
SELECT ID FROM GroupHIERARCHY
)
Run Code Online (Sandbox Code Playgroud)
但是,我得到一个错误,说:
";"附近的语法不正确 和')'附近的语法不正确
首先,对于;前面WITH.第二,对于)以前OR.我错过了什么?
你不能CTE像你想要的那样筑巢.你可以像这样使用它:
;WITH GroupHIERARCHY(ID)
AS ( SELECT ID
FROM tFirstTable te
WHERE te.LevelID <> 0
AND GroupID =-1
UNION ALL
SELECT t.ElementID
FROM tFirstTable AS t, tSecondTable,GroupHIERARCHY
WHERE t.TypeID=tSecondTable.TypeID
AND GroupHIERARCHY.ID= t.GroupID)
Select *
from tExampleTable
WHERE FirstParameter IN (SELECT ID FROM GroupHIERARCHY) OR
SecondParameter IN (SELECT ID FROM GroupHIERARCHY)
Run Code Online (Sandbox Code Playgroud)