sql 2000 数据库问题求教高手指导
现在有一个数据会按照日期每天生成一个表,例如从2013年10月1日开始到2013年10月31日, 每天会生成一个以日期命名的表 ,表名为YC20131001,YC20131001,YC20131002,YC20131003...YC20131031。
问题:
我如何在数据库的作业中,定期删除前一个月份的表。例如到了11月份我要删除YC20131001,YC20131001,YC20131002,YC20131003...YC20131031等表。目前想在数据的作业当中自动删除前一个月的表。
补充:
或者有其他的方法可以定期删除这些日期命名的表,求高手指点,谢谢!!! 数据库 sql 数据 表操作
[解决办法]
-- begin
use [数据库名]
declare @tabname varchar(50),@tsql varchar(100)
declare ap scroll cursor for
select 'YC'+convert(varchar,ds,112) 'tabname' from
(select dateadd(d,number,
stuff(
convert(varchar,dateadd(d,-1,
stuff(convert(varchar,getdate(),111)
,9,2,'01')),111)
,9,2,'01')) 'ds'
from master.dbo.spt_values
where type='P' and number<=32
) t
where datediff(m,t.ds,getdate())=1
open ap
fetch first from ap into @tabname
while(@@fetch_status<>-1)
begin
if exists(select 1 from sysobjects where xtype='U' and name=@tabname)
begin
select @tsql='drop table '+@tabname
exec(@tsql)
end
fetch next from ap into @tabname
end
close ap
deallocate ap
-- end
-- 注: 获取上月所有表名
select 'YC'+convert(varchar,ds,112) 'tabname' from
(select dateadd(d,number,
stuff(
convert(varchar,dateadd(d,-1,
stuff(convert(varchar,getdate(),111)
,9,2,'01')),111)
,9,2,'01')) 'ds'
from master.dbo.spt_values
where type='P' and number<=32
) t
where datediff(m,t.ds,getdate())=1
/*
tabname
--------------------------------
YC20130901
YC20130902
YC20130903
YC20130904
YC20130905
YC20130906
YC20130907
YC20130908
YC20130909
YC20130910
YC20130911
YC20130912
YC20130913
YC20130914
YC20130915
YC20130916
YC20130917
YC20130918
YC20130919
YC20130920
YC20130921
YC20130922
YC20130923
YC20130924
YC20130925
YC20130926
YC20130927
YC20130928
YC20130929
YC20130930
(30 row(s) affected)
*/
--1.建表
select * into YC20131001
from sys.objects
select * into YC20131031
from sys.objects
select * into YC20131003
from sys.objects
select * into YC20131002
from sys.objects
--2.找到要删除的表
declare @start varchar(10);
declare @end varchar(10);
set @start = '20131001'
set @end = '20131031'
select 'drop table dbo.' + t.name + ';'
from sys.tables t
where t.name like 'YC%' and
convert(varchar(10),substring(t.name,3,8),120) >= @start and
convert(varchar(10),substring(t.name,3,8),120) <= @end
/*
(无列名)
drop table dbo.YC20131001;
drop table dbo.YC20131031;
drop table dbo.YC20131003;
drop table dbo.YC20131002;
*/
--1.建表
select * into YC20131001
from sysobjects
select * into YC20131031
from sysobjects
select * into YC20131003
from sysobjects
select * into YC20131002
from sysobjects
--2.找到要删除的表
declare @start varchar(10);
declare @end varchar(10);
set @start = '20131001'
set @end = '20131031'
select 'drop table dbo.' + t.name + ';'
from sysobjects t
where t.name like 'YC%' and
t.xtype = 'U' and
convert(varchar(10),substring(t.name,3,8),120) >= @start and
convert(varchar(10),substring(t.name,3,8),120) <= @end
/*
(无列名)
drop table dbo.YC20131001;
drop table dbo.YC20131031;
drop table dbo.YC20131003;
drop table dbo.YC20131002;
*/