fzb215 发表于 2013-1-14 00:41:55

Sybase存储过程中查询动态表(按天分表)的处理

在ASE12.5.1环境下测试:
--exec sp_test_count '2009-10-01', '2009-10-08'--drop PROCEDUREsp_test_count    CREATE PROCEDURE sp_test_count(      @starttime datetime,      @endtime datetime)ASdeclare @totalCount numeric(18,0)   declare @tempCountnumeric(18,0)declare @day datetimedeclare @nextday datetimedeclare @datestr varchar(24)declare @sql varchar(200)declare @tempday datetimeselect @totalCount=0   select @tempCount=0   select @day=@starttimeselect @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 + " awhere 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:Number102, Severity15Server 'SYBASE', Line 1:Incorrect syntax near '='.
3.SQL Advantage中查看一条语句的执行时间,在这条语句的前后加上:
select convert(varchar(24) ,getdate(),109 )
页: [1]
查看完整版本: Sybase存储过程中查询动态表(按天分表)的处理