sql server 游标的简单示例

前端之家收集整理的这篇文章主要介绍了sql server 游标的简单示例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
感兴趣的小伙伴,下面一起跟随编程之家 jb51.cc的小编来看看吧。
sql代码如下:

alter procedure p_SlideAvg
(
@CityStr nvarchar(400),--城市字符串
@StationID nvarchar(10),--站点编号
@Type nvarchar(10),--类型
@sDate datetime,--开始时间
@eDate datetime    --结束时间
)
--set @CityStr='06'
--set @Type='O3'
--set @sDate='2008-03-20'
--set @eDate='2008-04-20'
as
declare @CityID nvarchar(10) --城市ID
--declare @StationID nvarchar(10)--站点ID
declare @channel_num nvarchar(10)--类型的channel_num

--先删除数据
declare @sqlD nvarchar(1000)
set @sqlD='delete from TAB_SlideAvg where stationID='''+@StationID+''' and Date_Time>='''+convert(varchar,@sDate,120)+''' and date_time<='''+convert(varchar,@eDate,120)+''''
exec sp_executesql @sqlD

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 b.id=c.station_id  
and upper(c.channel_name)=upper(@Type) 
and b.id=@StationID
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,@eDate)
declare @mDate datetime
--开始循环日期相加
while @i<@days
begin
    set @i=@i+1
    set @mDate=DATEADD(day,@i,@sDate) --循环的每一天的变量     print convert(varchar,@mDate,120)
    declare @h int
    set @h=0
    while @h<24--循环24小时
    begin
        declare @h24 datetime
        --set @h24=DATEADD(Hour,@h,@mDate)
        set @h24=dateadd(second,59,dateadd(minute,dateadd(hour,@mDate)))--时间添加上@h个小时 59分59秒 
        declare @oldH datetime
        set @oldH=DATEADD(Hour,-7,@h24) --当前小时数 减去7小时
        declare @sql1 nvarchar(1000)
        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)+''''
        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('''+@CityID+''','''+@StationID+''','''+@channel_num+''','''+convert(varchar,120)+''',@slideAvg,120)+''')'
            exec sp_executesql @sql2
        end
        set @h=@h+1 --时间每次循环+1
    end
end

-------------------------------------------------------------------------------------------------------------------------------
fetch next from C_SlideAvg into @CityID,@channel_num --取下一条记录
end
close C_SlideAvg--关闭游标
deallocate C_SlideAvg--销毁游标


---- 来自jb51.cc 

猜你在找的MsSQL相关文章