sqlserver一個循環圓的算法
阿新 • • 發佈:2019-04-17
RoCE etime rom sts 永遠 type set com val
在sqlserver中沒有數組的概率,我們就把數組的形式改成臨時表的形式,臨時表分為兩列,第一列就是id,即為數組的下標;第二列為值,即為數組的值;
上sql
ALTER PROCEDURE [dbo].[miao] @start datetime as begin set nocount on if exists(select * from sysobjects where name =‘#temp_clss‘) --查找命令 drop table #temp_clss --刪除 命令 if exists(select * from sysobjects where name =‘#temp_cls_dat‘) --查找命令 drop table #temp_cls_dat --刪除 命令 create table #temp_clss(id int,cls varchar(20)) insert into #temp_clss values (0,‘中‘) insert into #temp_clss values (1,‘中‘) insert into #temp_clss values (2,‘中‘) insert into #temp_clss values (3,‘早‘) insert into #temp_clss values (4,‘早‘) insert into #temp_clss values (5,‘早‘) insert into #temp_clss values (6,‘休‘) insert into #temp_clss values (7,‘夜‘) insert into #temp_clss values (8,‘夜‘) insert into #temp_clss values (9,‘夜‘) insert into #temp_clss values (10,‘休‘) insert into #temp_clss values (11,‘休‘) SELECT rowid1=identity(int,0,1),convert(char(10), DATEADD(dd, number, @start) - 2, 120) AS rptday into #temp_cls_dat FROM master .. spt_values WHERE type = ‘p‘ AND DATEDIFF(MI, DATEADD(dd, number, @start) - 24, @start) > 0 declare curs_dat cursor for select * from #temp_cls_dat /*結果表*/ create table #temp_result(日期 date,[甲值] varchar(20),[乙值] varchar(20),[丙值] varchar(20),[丁值] varchar(20)) declare @id_res int declare @id_dat int declare @dat date open curs_dat /*甲乙丙丁*/ declare @j varchar(20) declare @y varchar(20) declare @b varchar(20) declare @d varchar(20) fetch next from curs_dat into @id_dat,@dat while @@fetch_status=0 begin set @[email protected]_dat%12 /*甲乙丙丁*/ /*循環圓*/ if @id_res<12 begin select @j=cls from #temp_clss where [email protected]_res select @y=cls from #temp_clss where id=(([email protected]_res)%12) select @b=cls from #temp_clss where id=(([email protected]_res)%12) select @d=cls from #temp_clss where id=(([email protected]_res)%12) end insert into #temp_result values (@dat,@j,@y,@b,@d) fetch next from curs_dat into @id_dat,@dat end close curs_dat deallocate curs_dat select [日期], case when 甲值=‘早‘ then ‘甲值‘ when 乙值=‘早‘ then ‘乙值‘ when 丙值=‘早‘ then ‘丙值‘ when 丁值=‘早‘ then ‘丁值‘ else ‘error‘ end as [早], case when 甲值=‘中‘ then ‘甲值‘ when 乙值=‘中‘ then ‘乙值‘ when 丙值=‘中‘ then ‘丙值‘ when 丁值=‘中‘ then ‘丁值‘ else ‘error‘ end as [中], case when 甲值=‘夜‘ then ‘甲值‘ when 乙值=‘夜‘ then ‘乙值‘ when 丙值=‘夜‘ then ‘丙值‘ when 丁值=‘夜‘ then ‘丁值‘ else ‘error‘ end as [夜], case when 甲值=‘休‘ then ‘甲值‘ when 乙值=‘休‘ then ‘乙值‘ when 丙值=‘休‘ then ‘丙值‘ when 丁值=‘休‘ then ‘丁值‘ else ‘error‘ end as [休] from #temp_result drop table #temp_clss drop table #temp_cls_dat drop table #temp_result set nocount off end
在這裏,我的循環是以12為一個周期,所以
在這些地方都用到了%12,即取余的意思,一旦id大於等於12的時候我就用取余處理,這樣永遠就不會超過最大id,就可以理解為循環圓的形式。
sqlserver一個循環圓的算法