日期:2014-05-18  浏览次数:20403 次

SQL数据库的操作(只保存最新三条记录)
请问在创建的一个表中这样让它只能添加三条记录,如表中没超过三天记录时直接添加,如果超过的三条,如第四条记录,这样去掉最早添加的,反正就是只保存最新三条记录,请问这样的SQL 语句怎么写啊???非常感谢你们的!!!

------解决方案--------------------
SQL code

举个简单的例子

declare @rowCount int
select @rowCount=COUNT(*) from tb
if @rowCount<3
    begin
        insert into tb select GETDATE()
    end
else
    begin
        delete from tb where updateDate =(select MIN(updateDate) from tb)
        insert into tb select GETDATE()
    end

------解决方案--------------------
SQL code

create table tab (id int,name varchar(32))
go
insert tab select 1,'sdf' union all
select 2,'aerwe' union all
select 3,'werwerf'
go
create trigger instead_tri_name on tab
instead of insert
as
begin
    declare @id int,@name varchar(32)
    select @id=id,@name=name from inserted
    declare @count int,@curr_first int
    select @count=count(1) from tab
    select @curr_first=id from tab
    if @count=3
        begin
            delete from tab  where id= (select min(id) from tab)
            insert tab select @id,@name
        end
        else
        begin
            insert tab select @id,@name
        end
end

------解决方案--------------------
那就不创建触发器,判断以后在插入数据