sql :将一张表的数据插入到另一张表中同时要消除重复的数据

 现在有两张表要实现把表A中的数据插入到表B中,他们都有三个字段,而且表A中字段没有主键,而且还有重复数据的字段,但是对应表b中这个字段不需要重复而且还需要是唯一的,这时候我想了一个简单又快速的方法,就是利用游标一行一行的读取数据,讲读取的数据插入一个临时表中,临时表我设置了一个自增长的id这样就可以通过id是否相等来消除重复(即通过id最大值或者最小值方法)代码示例如下:

select * from declare @icard varchar(20)
declare @Num varchar(20)
declare @intID varchar(20)
declare @newtable table(id int identity(1,1),icard varchar(20),iname varchar(20),iage varchar(20))
select identity(int,1,1) as id,* into newtable from A
declare cursor_xs cursor for
select icard,iname,iage from newtable where id in (select max(id) from newtable group by [icard])
open cursor_xs
fetch next from cursor_xs into @icard,@Num,@intID
while  @@fetch_status=0
begin
insert into B values(@icard,@Num,@intID)
fetch next from cursor_xs into @icard,@Num,@intID
end
close cursor_xs
deallocate cursor_xs
drop table newtable

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值