首页 > 代码库 > Tsql生成序列、日期序列

Tsql生成序列、日期序列

--方法1SET NOCOUNT ONUSE tempdbGOIF OBJECT_ID(dbo.nums)IS NOT NULLDROP TABLE dbo.nums;GOCREATE TABLE dbo.nums(n INT NOT NULL PRIMARY KEY);DECLARE @max AS INT,@rc AS INTSET @max=1000000SET @rc=1INSERT INTO nums VALUES (1);WHILE @rc*2<=@maxBEGIN    INSERT INTO nums SELECT n+@rc FROM nums;    SET @rc=@rc*2END--SELECT n+@rc FROM nums WHERE n+@rc<=@maxGODECLARE @s AS DATETIME,@e AS DATETIMESET @s=20140501SET @e=20141231SELECT @s+n-1 AS dt FROM nums WHERE n<=DATEDIFF(DAY,@s,@e)+1SELECT * FROM nums  WHERE n<10GO--方法2IF object_id(fn_nums) IS NOT NULLBEGIN     PRINT Dropping function fn_nums    DROP FUNCTION fn_nums    IF @@ERROR = 0 PRINT Function fn_nums droppedENDgoCREATE FUNCTION fn_nums(    @n AS BIGINT) RETURNS TABLE    AS RETURNWITH    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<=@nGODECLARE @s AS DATETIME,@e AS DATETIMESET @s=20140501SET @e=20141231SELECT @s+n-1 AS dt FROM dbo.fn_nums(DATEDIFF(DAY,@s,@e))AS nums;SELECT * FROM  dbo.fn_nums(10)