当前位置: 代码迷 >> Sql Server >> SQL数据库的操作(只保存最新三条记录),该怎么解决
  详细解决方案

SQL数据库的操作(只保存最新三条记录),该怎么解决

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

------解决方案--------------------
SQL code
举个简单的例子declare @rowCount intselect @rowCount=COUNT(*) from tbif @rowCount<3    begin        insert into tb select GETDATE()    endelse    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))goinsert tab select 1,'sdf' union allselect 2,'aerwe' union allselect 3,'werwerf'gocreate trigger instead_tri_name on tabinstead of insertasbegin    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        endend
------解决方案--------------------
那就不创建触发器,判断以后在插入数据
  相关解决方案