SQL Server使用触发器删除重复的列(Delete duplicate rows using cursor in SQL Server)

这里我使用的是cursor 加上top函数来删除重复的列的。


先建立一个表格


Create table employees(code nvarchar(20) Primary key, value nvarchar(200), description nvarchar(1000));

插入数据

Insert into employees(code, value, description) values('garcon1986', 'developer', 'he works in IT company.'); Insert into employees(code, value, description) values('garcon1986', 'developer', 'he works in IT company.'); Insert into employees(code, value, description) values('garcon1986', 'developer', 'he works in IT company.'); Insert into employees(code, value, description) values('garcon1986', 'developer', 'he works in IT company.'); Insert into employees(code, value, description) values('charles', 'IT manager', 'he owns an IT company.'); Insert into employees(code, value, description) values('charles', 'IT manager', 'he owns an IT company.'); Insert into employees(code, value, description) values('charles', 'IT manager', 'he owns an IT company.');

以Code和Value两列为基础,使用cursor和top函数删除重复的列

IF CURSOR_STATUS('local','employeesCursor')>0 BEGIN CLOSE employeesCursor DEALLOCATE employeesCursor END; DECLARE @Count INT; DECLARE @Code nvarchar(20); DECLARE @Value nvarchar(200); DECLARE employeesCursor CURSOR FOR SELECT Code, Value, Count(*) - 1 FROM employees GROUP BY Code, Value HAVING Count(*) > 1; BEGIN TRAN OPEN employeesCursor FETCH NEXT FROM employeesCursor INTO @Code, @Value, @Count WHILE @@FETCH_STATUS = 0 BEGIN DELETE TOP(@Count) FROM employees WHERE Code = @Code AND Value = @Value FETCH NEXT FROM employeesCursor INTO @Code, @Value, @Count END CLOSE employeesCursor DEALLOCATE employeesCursor COMMIT;





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值