sql server 游标实例:循环表内数据,并根据参数 查询其他表内数据,拼接SQL 插入另一个表示例
2022-11-12 09:55:37
内容摘要
这篇文章主要为大家详细介绍了sql server 游标实例:循环表内数据,并根据参数 查询其他表内数据,拼接SQL 插入另一个表示例,具有一定的参考价值,可以用来参考一下。
对此感兴趣的
文章正文
这篇文章主要为大家详细介绍了sql server 游标实例:循环表内数据,并根据参数 查询其他表内数据,拼接SQL 插入另一个表示例,具有一定的参考价值,可以用来参考一下。
对此感兴趣的朋友,看看idc笔记做的技术笔记。SQL代码如下:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | <code class = "sql" > declare @CityStr nvarchar(400) declare @Type nvarchar(10) declare @sDate datetime --开始时间 declare @eDate datetime --结束时间 declare @CityID nvarchar(10) declare @StationID nvarchar(10) declare @channel_num nvarchar(10) set @CityStr= '06' set @Type= 'O3' set @sDate= '2008-03-01' set @eDate= '2013-01-20' declare C_SlideAvg cursor for select a.id as CityID,b.id as StationId,c.channel_num from TAB_BASE_GROUP as a,TAB_STATION_BASEINFO as b, tab_channel_baseinfo as c where a.id=b.group_id and a.id in(@CityStr) and b.id=c.station_id and upper(c.channel_name)=upper(@Type) and c.channel_state = 1 open C_SlideAvg --打开游标 fetch next from C_SlideAvg into @CityID,@StationID,@channel_num while (@@fetch_status=0) begin ------------------------------------------------------------------------------------------------------------------------------ declare @days int --间隔的天数 declare @i int set @i=0 set @days=datediff(day,@sDate,@eDate) declare @mDate datetime --开始循环日期相加 while @i<@days begin set @i=@i+1 set @mDate=DATEADD(day,@i,@sDate) --循环的每一天的变量 declare @h int set @h=0 while @h<24--循环24小时 begin declare @h24 datetime set @h=@h+1 --时间每次循环+1 set @h24=DATEADD(Hour,@h,@mDate) declare @oldH datetime set @oldH=DATEADD(Hour,-7,@h24) --当前小时数 减去8小时 declare @sql1 nvarchar(1000) --set @sql1= 'select avg(val) as SlideAvg from S' +@StationID+ 'HN where channel_num=' '' +@channel_num+ '' ' and date_time>=' +convert(varchar,@oldH,120)+ ' and date_time<=' '' +convert(varchar,@h24,120)+ '' '' declare @slideAvg real set @sql1= 'select @slideAvg=avg(val) from S' +@StationID+ 'HN where channel_num=' '' +@channel_num+ '' ' and date_time>=' '' +convert(nvarchar,@oldH,120)+ '' ' and date_time<=' '' +convert(nvarchar,@h24,120)+ '' '' -- print @sql1 exec sp_executesql @sql1,N '@slideAvg real output' ,@slideAvg output IF @slideAvg IS NOT NULL AND @slideAvg<> '' begin declare @sql2 nvarchar(1000) set @sql2= 'insert into Tab_Slideavg values(' '06' ',' '' +@StationID+ '' ',' '' +@channel_num+ '' ',' '' +convert(varchar,@h24,120)+ '' ',' '' +convert(varchar,@slideAvg,120)+ '' ')' exec sp_executesql @sql2 end end end ------------------------------------------------------------------------------------------------------------------------------- fetch next from C_SlideAvg into @CityID,@StationID,@channel_num --取下一条记录 end close C_SlideAvg--关闭游标 deallocate C_SlideAvg ---- 来自www.512pic.com </code> |
注:关于sql server 游标实例:循环表内数据,并根据参数 查询其他表内数据,拼接SQL 插入另一个表示例的内容就先介绍到这里,更多相关文章的可以留意
代码注释