求一个SQL语句的写法!望高手们帮助!!
有这样一个需求,每天从接口数据TXT文本导入一张表中,从该表中删除相同帐号中日期小于当天的记录.
如 帐号 日期
原表中有一条记录:0001 20070102
现导入一条记录: 0001 20070105
需删除帐号0001 20070102那条记录,保留0001 20070105这条记录.
输出的结果是只有最近更新的帐号记录.记录数大约三万条
由于是在同一表中进行删除操作,这样的SQL能写吗?我写一个SQL,但总是提示超时.
delete from adkfh_1129 where cast(zhangh as varchar(21)) + zhjyrq not in
( select cast(b.zhangh as varchar(21)) + max(b.zhjyrq) as rq from adkfh_1129 b group by b.zhangh )
------解决方案--------------------create trigger tr_insert
for insert
as
delete from table a,inserted b where a.帐号=b.帐号 and a.日期 <b.日期
go
------解决方案--------------------试一下
delete adkfh_1129 from adkfh_1129 a where exists(select 1 from adkfh_1129 b
where a.zhjyrq <b.zhjyrq and a.zhangh=b.zhangh)
------解决方案--------------------新建一表结构与相同的表t2导入数据。加一存储过程,判断增加至adkfh_1129中还是更新至adkfh_1129中
create procedure pro_test
as
select count(1) from adkfh_1129 inner join t2 where
建个触发器
TRIGGER [tri_test]
ON adkfh_1129
INSTEAD OF INSERT
AS
BEGIN
declare @i int
select @i=count(1) from adkfh_1129 inner join inserted on adkfh_1129.zhangh=inserted.zhangh
if @@rowcount > 0
UPDATE P SET
P.zhjyrq = I.zhjyrq
FROM adkfh_1129 AS P INNER JOIN Inserted AS I
ON P.zhangh = I.zhangh
END
------解决方案--------------------用判断真假的方式效率比较高
delete a
from adkfh_1129 a
where exists(select 1 from adkfh_1129 where zhangh=a.zhangh and zhjyrq> a.zhjyrq)