SQL Server 完成數字幫助表實例代碼。本站提示廣大學習愛好者:(SQL Server 完成數字幫助表實例代碼)文章只能為提供參考,不一定能成為您想要的結果。以下是SQL Server 完成數字幫助表實例代碼正文
數字幫助表是一個持續整數的數列,平日用來完成多種分歧的查詢義務。年夜多分兩類:足夠年夜物理數字表和表函數,前者可以稱為靜態的,後者可以稱為靜態且按需臨盆。
物理數字表
物理數字表平日存在一個物理表,表記載絕對足夠年夜,相干的T-SQL代碼以下:
IF OBJECT_ID(N'dbo.Nums', 'U') IS NOT NULL BEGIN DROP TABLE dbo.Nums; END GO CREATE TABLE dbo.Nums ( Num INT NOT NULL, CONSTRAINT PK_U_CL_Nums_Num PRIMARY KEY CLUSTERED ( Num ASC ) ); GO INSERT INTO dbo.Nums (Num) SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS RowNum FROM master.dbo.spt_values; GO
留意:若何填充物理數字表的辦法許多,為了演示感化應用了一種。
測試的T-SQL代碼以下:
1 SELECT Num 2 FROM dbo.Nums; 3 GO
履行後的查詢成果以下:
表函數
表函數完成應用穿插銜接和CTE,SQL Server 2005和以上版本的T-SQL代碼以下:
IF OBJECT_ID(N'dbo.ufn_GetNums', N'IF') IS NOT NULL BEGIN DROP TABLE dbo.ufn_GetNums; END GO --================================== -- 功效: 獲得指定規模的數字數列 -- 解釋: 穿插最初層級的CTE獲得的數據行:在L級(從0開端計數)獲得的行的總數為2^2^L。 -- 例如:在5級就會獲得4 294 967 596行。5級的CTE供給了跨越40億的行。 -- 作者: XXX -- 創立: yyyy-MM-dd -- 修正: yyyy-MM-dd XXX 修正內容描寫 --================================== CREATE FUNCTION dbo.ufn_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 (@bintHigh - @bintLow + 1) @bintLow + RowNum - 1 AS Num FROM Nums ORDER BY RowNum ASC; GO
SQL Server 2012增長了有關分頁的新特征,相干的T-SQL代碼以下:
IF OBJECT_ID(N'dbo.ufn_GetNums2', N'IF') IS NOT NULL BEGIN DROP TABLE dbo.ufn_GetNums2; END GO --================================== -- 功效: 獲得指定規模的數字數列 -- 解釋: 穿插最初層級的CTE獲得的數據行:在L級(從0開端計數)獲得的行的總數為2^2^L。 -- 例如:在5級就會獲得4 294 967 596行。5級的CTE供給了跨越40億的行。 -- 作者: XXX -- 創立: yyyy-MM-dd -- 修正: yyyy-MM-dd XXX 修正內容描寫 --================================== CREATE FUNCTION dbo.ufn_GetNums2 ( @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 @bintLow + RowNum - 1 AS Num FROM Nums ORDER BY RowNum ASC OFFSET 0 ROWS FETCH FIRST @bintHigh - @bintLow + 1 ROWS ONLY; GO
以函數ufn_GetNums為例,演示相干的後果。獲得指定規模的數字序列的T-SQL代碼以下:
SELECT Num FROM dbo.ufn_GetNums(11, 20); GO
履行後的查詢成果以下:
博友若有其他更好的處理計劃,也請不惜賜教,萬分感激。
參考清單列表
1、《Microsoft SQL Server 2012 High-Performance T-SQL Using Window Functions》 作者 Itzik Ben-Gan(美國)(SQL Server Inside 有關書本的作者)
感激浏覽,願望能贊助到年夜家,感謝年夜家對本站的支撐!