/*==================================*/ /* 功能: 获取指定范围的数字数列*/ /* 说明: 交叉最后层级的CTE得到的数据行:在L级(从0开始计数)得到的行的总数为2^2^L。*/ /* 例如:在5级就会得到4 294 967 596行。5级的CTE提供了超过40亿的行。 */ /* 作者: 网上摘抄*/ /* 创建: 2016-07-16*/ /* 修改: */ /* 2016-08-19 对 @bintHigh、@bintLow 进行判断,防止TOP子句含有无效的值 */ /*==================================*/ CREATE FUNCTION dbo.fn_GetNums ( @bintLow BIGINT, @bintHigh BIGINT ) RETURNS TABLE AS RETURN ( WITH L0 AS (SELECT c FROM (VALUES(1), (1)) AS LO(c)), L1 AS (SELECT 1 AS c FROM L0 AS T CROSS JOIN L0 AS T2), L2 AS (SELECT 1 AS c FROM L1 AS T CROSS JOIN L1 AS T2), L3 AS (SELECT 1 AS c FROM L2 AS T CROSS JOIN L2 AS T2), L4 AS (SELECT 1 AS c FROM L3 AS T CROSS JOIN L3 AS T2), L5 AS (SELECT 1 AS c FROM L4 AS T CROSS JOIN L4 AS T2), Nums AS (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS RowNum FROM L5) SELECT TOP (CASE WHEN @bintHigh >=@bintLow THEN @bintHigh - @bintLow + 1 ELSE 0 END) @bintLow + RowNum - 1 AS Num FROM Nums ORDER BY RowNum ASC ) GO