我目前正在使用以下方法创建即时表格
DECLARE @startnum INT=1000
DECLARE @endnum INT=1004
;
WITH gen AS (
SELECT @startnum AS num
UNION ALL
SELECT num+1 FROM gen WHERE num+1<=@endnum
)
SELECT * FROM gen
option (maxrecursion 0)
我想知道是否有办法让我在子查询中利用此表进行联接。例如,如何用上表替换以下代码中的a2。
select a1.*, a2.*
from
(select
1000 as v1
union all
select
1001 as v1
union all
select
1003 as v1)a1
left join
(select
1000 as v2
union all
select
1001 as v2
union all
select
1003 as v2
union all
select
1004 as v2)a2
ON a1.v1=a2.v2
谢谢。
答案 0 :(得分:0)
尝试如下所示,只需添加另一个cte并使用join
DECLARE @startnum INT=1000
DECLARE @endnum INT=1004
;
WITH gen AS (
SELECT @startnum AS num
UNION ALL
SELECT num+1 FROM gen WHERE num+1<=@endnum
),cte as
(
SELECT * FROM gen
) , cte1 as
(
select a1.* from
(select
1000 as v1
union all
select
1001 as v1
union all
select
1003 as v1
)a1
) select cte.*,cte1.* from cte join cte1 on cte.num=cte1.v1
答案 1 :(得分:0)
使用CTE:
WITH gen AS (
SELECT @startnum AS num
UNION ALL
SELECT num + 1
FROM gen
WHERE num + 1 <= @endnum
)
SELECT
FROM gen JOIN
a1
ON a1.v1 = gen.num
OPTION (MAXRECURSION 0);
唯一的窍门是OPTION
必须位于整个查询的结尾。