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 )
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值