我如何在这样的查询中使用 with?有没有办法在 TableList 中使用 tableIds?我可以将它们视为子查询吗?
select * from TestTable where tableId in
(WITH TableList (tableId)
AS
(
SELECT tableId FROM OldTable WHERE tableId=5 and IsDeleted = 0
UNION ALL
SELECT t.tableId From OldTable as t
INNER JOIN TableList as p
ON t.ParenTableId = p.TableId
WHERE t.IsDeleted = 0
)
SELECT tableId FROM TableList
)
编辑:为了说明为什么我不能在 sql 的第一条语句中使用 with。
select TableId, IsDeleted,
(
select count(OtherId) OtherTable
where otherTableId in
(WITH TableList (tableId)
AS
(
SELECT tableId FROM OldTable WHERE tableId=5 and IsDeleted = 0
UNION ALL
SELECT t.tableId From OldTable as t
INNER JOIN TableList as p
ON t.ParenTableId = p.TableId
WHERE t.IsDeleted = 0
)
SELECT tableId FROM TableList
)
) as Ex1
from TestTable where tableId in (1,2,3)
我认为这说明了为什么我试图在 sql 查询中间使用 with 子句。