本文主要是介绍Sybase存储过程中查询动态表(按天分表)的处理,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在ASE12.5.1环境下测试:
--exec sp_test_count '2009-10-01', '2009-10-08'
--drop PROCEDURE sp_test_count
CREATE PROCEDURE sp_test_count
(
@starttime datetime,
@endtime datetime
)
AS
declare @totalCount numeric(18,0)
declare @tempCount numeric(18,0)
declare @day datetime
declare @nextday datetime
declare @datestr varchar(24)
declare @sql varchar(200)
declare @tempday datetime
select @totalCount=0
select @tempCount=0
select @day=@starttime
select @nextday=@endtime
create table #t1(total numeric(18,0)) --创建临时表,用来存放所需统计数据
while(@day<@nextday)
begin
select @tempday=@day
--convert转换后的结果为2009/10/01
select @datestr=convert(varchar(20), @day,111 )
--获得日期的字符串格式:20090720,以匹配t_test_20091001,t_test_20091002 ... 07
select @datestr=substring(@datestr,1,4)+substring(@datestr,6,2)+substring(@datestr,9,2)
select @sql ="insert into #t1 select count(*) from t_test_"+@datestr + " a where a.name='abc' and exists (select number from t_test2 where a.no=number)"
exec(@sql)
--对日期中的分量——天进行加1
select @day=dateadd(dd ,1, @tempday)
end
select @totalCount=sum(total) from #t1
drop table #t1
注:
1.exec(@sql)不能返回查询结果,所以需要将动态查询结果先插入到临时表,再select * from #t1返回结果。
2.匹配好的t_test_20091001,必须进行重命名,如上面的a,a.name。否则,会报如下的错误:
Server Message: Number 102, Severity 15
Server 'SYBASE', Line 1:
Incorrect syntax near '='.
3.SQL Advantage中查看一条语句的执行时间,在这条语句的前后加上:
select convert(varchar(24) , getdate(),109 )
这篇关于Sybase存储过程中查询动态表(按天分表)的处理的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!