首页 > 代码库 > 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=‘20140501‘SET @e=‘20141231‘SELECT @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 dropped‘ENDgoCREATE 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=‘20140501‘SET @e=‘20141231‘SELECT @s+n-1 AS dt FROM dbo.fn_nums(DATEDIFF(DAY,@s,@e))AS nums;SELECT * FROM dbo.fn_nums(10)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。