SQL Server 2005 T-SQL Query学习(四)
栏目:MSSQL 来源:网络 关注:0 时间:2019-08-21
建立数字辅助表(即是1-N的数字按顺序组成的表),关于如何建立这些辅助表,很有代表性一些例子。
比如,我要建立一个1,000,000行的数字表:
CREATE TABLE dbo.Nums(n INT NOT NULL PRIMARY KEY);
DECLARE @max AS INT, @rc AS INT;
SET @max = 1000000;
SET @rc = 1;
INSERT INTO Nums VALUES(1);
WHILE @rc * 2 <= @max
BEGIN
INSERT INTO dbo.Nums SELECT n + @rc FROM dbo.Nums;
SET @rc = @rc * 2;
END
INSERT INTO dbo.Nums
SELECT n + @rc FROM dbo.Nums WHERE n + @rc <= @max;
这种方式非常巧妙,它并不是一个一个的循环插入,而是一次插入很多行,{1},{2},{3,4},{5,6,7,8}。。。
为什么这样会快呢?
是因为它节省了跟比较其他可用解决方案进行比较和记录这些日志的时间。
CTE的递归的解决方案:
DECLARE @n AS BIGINT;
SET @n = 1000000;
WITH Nums AS
(
SELECT 1 AS n
UNION ALL
SELECT n + 1 FROM Nums WHERE n < @n
)
SELECT n FROM Nums
OPTION(MAXRECURSION 0);--为了移除默认100的递归限制
有个更优的CTE的解决方案,就是先生成很多行,然后用ROW_NUMBER进行计算,再选择ROW_NUMBER这列的值就可以了。
代码如下:
DECLARE @n AS BIGINT;
SET @n = 1000000;
WITH Base AS
(
SELECT 1 AS n
UNION ALL
SELECT n + 1 FROM Base WHERE n < CEILING(SQRT(@n))
),
Expand AS
(
SELECT 1 AS c
FROM Base AS B1, Base AS B2
),
Nums AS
(
SELECT ROW_NUMBER() OVER(ORDER BY c) AS n
FROM Expand
)
SELECT n FROM Nums WHERE n <= @n
OPTION(MAXRECURSION 0);
利用笛卡尔积进行不断的累加,达到了22n行。
最后,一个函数用于生成这样的数字表:
代码如下:
CREATE FUNCTION dbo.fn_nums(@n AS BIGINT) RETURNS TABLE
AS
RETURN
WITH
L0 AS(SELECT 1 AS c UNION ALL SELECT 1),
L1 AS(SELECT 1 AS c FROM L0 AS A, L0 AS B),
L2 AS(SELECT 1 AS c FROM L1 AS A, L1 AS B),
L3 AS(SELECT 1 AS c FROM L2 AS A, L2 AS B),
L4 AS(SELECT 1 AS c FROM L3 AS A, L3 AS B),
L5 AS(SELECT 1 AS c FROM L4 AS A, L4 AS B),
Nums AS(SELECT ROW_NUMBER() OVER(ORDER BY c) AS n FROM L5)
SELECT n FROM Nums WHERE n <= @n;
GO
本文标题:SQL Server 2005 T-SQL Query学习(四)
本文地址:http://www.q0738.com/mssql/1371.html
- SQL Server 2005 ERROR:3145解决办法(备份集中的数据库备份与现有的数据库不同)
- SQL Server 2005的排名函数使用小结
- MSSQL Server 2005在networkservice权限运行附加数据库报(Microsoft SQL Ser...
- Win7安装软件时无法连接SQL Server解决方法
- SQL Server 2005的维护计划无法删除的解决方法
- SQL Server 2005 T-SQL Query学习(四)
- SQL Server 2005中使用SQL语句对xml文件和其数据的操作
- SQL Server 2005中使用row_number在一个查询中删除重复记录
- SQL Server 2005通用分页存储过程及多表联接应用
- SQLsever为标识列指定显式值