程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> SqlServer數據庫 >> 關於SqlServer >> Sql Server實現按時間統計存儲過程(涉及臨時表,動態Sql語句,Cast用法,Sp_Execute 多參數調用,游標技術等)

Sql Server實現按時間統計存儲過程(涉及臨時表,動態Sql語句,Cast用法,Sp_Execute 多參數調用,游標技術等)

編輯:關於SqlServer

代碼:

ALTER                   Procedure UserSiteNowDataHourTotalVIEw_List(
@StartTime varchar(25),
@EndTime varchar(25),
@SiteID int
)
AS

declare @SQLString nvarchar(200)
declare @SQLTemp nvarchar(2000)
declare @TotalNum nvarchar(25)
set @StartTime=replace(@StartTime,''-'',''.'')
set @EndTime=replace(@EndTime,''-'',''.'')
--set @SQLString=N''SELECT case when [TotalNum]=null then 0 else [TotalNum] End from UserSiteNowDataHourTotalVIEw WHERE (VisitTime between ''''''+@StartTime
--定義全局游標 declare   tb   cursor   global for

set @SQLString=N''SELECT @TotalNum=sum([TotalNum]) from UserSiteNowDataHourTotalVIEw WHERE (VisitTime between ''''''+@StartTime
set @SQLString=@SQLString+N'''''' and ''''''+@EndTime+'''''')''

--if @SiteID!=0
--set @SQLString=@SQLString+N'' and SiteID=''+cast(@SiteID as nvarchar)
--建立臨時表
Create Table #Hour_Temp(
ID int IDENTITY(1,1) NOT NULL,
[HourNum] int,
[TotalNum] int,
primary key(ID)
)

declare @i int

set @i=0
while @i<24
begin
--set @SQLTemp=N''declare   tb   cursor for ''+@SQLString
set @SQLTemp=@SQLString
set @SQLTemp=@SQLTemp+N'' and [Hour]=''+cast(@i as nvarchar)
set @TotalNum = null
execute SP_Executesql @SQLTemp,N''@TotalNum   INT   output'',@TotalNum   OUTPUT
if @TotalNum is null
set @TotalNum=0

print @TotalNum

/*
@S,N''@RET   INT   output'',@RET   OUTPUT
open   tb  
  fetch   tb    
  close   tb  
  deallocate   tb
*/
insert into #Hour_Temp(HourNum,TotalNum) values (@i,@TotalNum)

--insert into #Hour_Temp(HourNum,TotalNum) values(@i,@i)
--set @SQLTemp=@SQLTemp+N'' union all ''+@SQLString+N'' and DatePart(hh,

VisitTime)=''+cast(@i as nvarchar)
set @i=@i+1
end

--exec sp_executesql @SQLTemp
select * from #Hour_Temp order by HourNum asc

Sp_ExecuteSql多參數調用演示

Create Procedure TestExecuteSql
AS

declare @Hour int
declare @tablename varchar(200)
declare @sql nvarchar(200)
declare @value int

set @tablename=''UserSiteNowDataHourTotalVIEw''
set @Hour=15
--set @sql=N''select @value=TotalNum from ''+@tablename+'' where [Hour]=''+cast(@Hour as nvarchar)
set @sql=N''select @value=TotalNum from ''+@tablename+'' where [Hour]=@Hour''
--set @sql=@sql
execute sp_Executesql @sql,N''@value int output,@Hour int'',@value output,@Hour=12

print @value

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved