1. 程式人生 > >刪除表的重複記錄(利用遊標)

刪除表的重複記錄(利用遊標)

create table a_dist(id int,name varchar(20))

insert into a_dist values(1,'abc')
insert into a_dist values(1,'abc')
insert into a_dist values(1,'abc')
insert into a_dist values(1,'abc')

exec up_distinct 'a_dist','id'

select * from a_dist

create procedure up_distinct(@t_name varchar(30),@f_key varchar(30))
--f_key表示是分組欄位﹐即主鍵欄位
as
begin
declare @max integer,@id varchar(30) ,@sql varchar(7999) ,@type integer
select @sql = 'declare cur_rows cursor for select

'[email protected]_key+' ,count(*) from ' [email protected]_name +' group by ' [email protected]_key +' having count(*) > 1'
exec(@sql)
open cur_rows
fetch cur_rows into @id,@max
while @@fetch_status=0
begin
select @max = @max -1
set rowcount @max
select @type = xtype from syscolumns where id=object_id(@t_name) and
[email protected]_key

if @type=56
select @sql = 'delete from '[email protected]_name+' where ' + @f_key+' = '+ @id
if @type=167
select @sql = 'delete from '[email protected]_name+' where ' + @f_key+' = '+''''+ @id +''''
exec(@sql)
fetch cur_rows into @id,@max
end
close cur_rows
deallocate cur_rows
set rowcount 0
end

select * from systypes
select * from syscolumns where id = object_id('a_dist')



Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=621635