WITH语句相当于建立了一张临时虚拟表,但是不会被物理创建,用完即销毁。
示例
利用临时表生成连续的数字表
WITH
T1 AS(
SELECT n = 1
UNION ALL
SELECT n = 1
), --2条
T2 AS (
SELECT n = 1
FROM T1 A
CROSS JOIN T1 B
), --4条
T3 AS (
SELECT n = 1
FROM T2 A
CROSS JOIN T2 B
), --16条
T4 AS (
SELECT n = 1
FROM T3 A
CROSS JOIN T3 B
), --256条
T5 AS (
SELECT n = 1
FROM T4 A
CROSS JOIN T4 B
) --(2的(N-1)次方)的平方
SELECT A.RN
FROM(
SELECT ROW_NUMBER() OVER(ORDER BY n) RN
FROM T5
) A
WHERE A.RN < 10000
示例
利用INTO直接新建一个临时表存select出来的数据
select * into #xxxx from A