1. 程式人生 > >構建序數表值函式

構建序數表值函式

IF OBJECT_ID('dbo.Fun_GetNumList') IS NOT NULL
	DROP FUNCTION dbo.Fun_GetNumList
GO
-- =============================================
-- Author:		yenange
-- Create date: 2018-11-26
-- Description:	構建序數 表值函式
-- =============================================
CREATE FUNCTION dbo.Fun_GetNumList 
(
	@n BIGINT	
)
RETURNS TABLE
AS
RETURN 
(
	WITH cte AS (
			SELECT 1 AS n UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5
			UNION ALL 
			SELECT 6 AS n UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9 UNION ALL SELECT 10
	)
	--1000
	,cte2 AS (
		SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS rid FROM cte AS a CROSS APPLY cte AS b CROSS APPLY cte AS c	
	)
	--10萬
	,cte3 AS (
		SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS rid FROM cte2 AS a CROSS APPLY cte2 AS b
	)
	--100億
	,cte4 AS (
		SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS rid FROM cte2 AS a CROSS APPLY cte2 AS b CROSS APPLY cte2 AS c 
		CROSS APPLY
		cte AS d 
	)
	SELECT * FROM cte2 WHERE @n<=1000 AND rid<
[email protected]
UNION ALL SELECT * FROM cte3 WHERE @n>1000 AND @n<=100000 AND rid<[email protected] UNION ALL SELECT * FROM cte4 WHERE @n>100000 AND rid<[email protected] ) GO