关于SQL Server2000 触发器的问题
有个TEST表,每10分钟写进1次数据,想最多存储30天的数据,也就是4320条数据,
存满后,当新数据写进去,最早时间存储的旧数据将被删除。表内始终保持30天的数据。请问利用触发器怎样做?麻烦语句写详细点,谢谢。(表列有:id tmdate name)
------解决方案--------------------用作业比较合适,作业执行语句
delete test where tmdate <dateadd(day,-30,getdate())
每天执行一次
触发器也可以,大概代码:
create trigger tr_test_insert
on test
for inserted
as
set nocount on
delete test where tmdate <dateadd(day,-30,getdate())
go
------解决方案--------------------create trigger T on test
for insert
as
Begin
Declare @Row int
select @Row =count(*)
from test
if @Row = 4320
delete Test
where ID in(select top 10 ID from Test)
End
------解决方案--------------------create trigger T on test
for insert
as
Begin
Declare @Row int
select @Row =count(*)
from test
if @Row = 4320
delete Test
where //取最早一条记录
End
只删掉对大一条即可
------解决方案----------------------改进一下,兼容多条.
create trigger T on test
for insert
as
Begin
Declare @Row int
declare @insertrow int
declare @sql varchar(1000)
set @sql = ' '
select @Row =count(*) from test
select @insertrow = count(*) from inserted
if @Row = 4320
begin
set @sql = 'delete from test where id in (select top '+rtrim(@insertrow)+ ' id from test order by tmdate desc) '
exec(@sql)
end
End
------解决方案--------------------楼上的inserted--多了ed去掉
create trigger tr_test_insert
on test
for insert
as
delete a from test as a
where (select count(*) from test where tmdate <a.tmdate) <4320--保留4320
------解决方案--------------------删除30天前的数据由作业调度来完成比较好(设置每天的执行时间)
用以下代码调度
delect test
where convert(varchar(10),tmdate,120) <convert(varchar(10),getdate()-30,120) <()