SQL虚拟数字辅助表
虚拟数字辅助表是一个整数序列,可以用来完成多种不同的任务,如生成日期跟时间值序列,及分裂值列表。要用查询逻辑产生一个大的整数序列,可以使用交叉连接(cross join)。
交叉联接(cross join)执行两个表的笛卡尔积(就是把表A和表B的数据进行一个N*M的组合)。也就是说,它匹配一个表与另一个表中的每一行;我们不能通过使用ON子句在交叉联接指定谓词,虽然我们可以使用WHERE子句来实现相同的结果,这是交叉联接基本上是作为一个内部联接了。
交叉联接相对于内部联接使用率较低,而且两个大表不应该进行交叉联接,因为这将导致一个非常昂贵的操作和一个非常大的结果集。
create function dbo.GetNums(@low as bigint,@high as bigint) returns table as return with L0 as (SELECT c FROM (values(1),(1)) as D(c)), L1 as (select 1 as c from L0 cross join L0 as B), L2 as (select 1 as c from L1 cross join L1 as B), L3 as (select 1 as c from L2 cross join L2 as B), L4 as (select 1 as c from L3 cross join L3 as B), L5 as (select 1 as c from L4 cross join L4 as B), Nums as (select ROW_NUMBER() over(order by (select null)) as rownum from L5) select @low+rownum-1 as n from Nums order by rownum offset 0 rows fetch first @high-@low+1 rows only
select * from dbo.GetNums(10,20)