Guest User

Untitled

a guest
Jun 20th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.81 KB | None | 0 0
  1. create table test (id int identity primary key, val varchar(20) )
  2. --id is a pk for the cursor so it can update using "where current of"
  3.  
  4. -- name a is not duplicated
  5. -- name b is duplicated 3 times
  6. -- name c is duplicated 2 times
  7.  
  8. insert test values('name a')
  9. insert test values('name b')
  10. insert test values('name c')
  11. insert test values('name b')
  12. insert test values('name b')
  13. insert test values('name c')
  14.  
  15. begin tran; -- Computed table expressions require the statement prior to end with ;
  16.  
  17. with cte(val,row) as (
  18.  
  19. select val, row_number() over (partition by val order by val) row
  20. --partiton is important. it resets the row_number on a new val
  21. from test
  22. where val in ( -- only return values that are duplicated
  23. select val
  24. from test
  25. group by val
  26. having count(val)>1
  27. )
  28. )
  29. update cte set val = val + ltrim(str(row))
  30. --ltrim(str(row)) = converting the int to a string and removing the padding from the str command.
  31.  
  32. select * from test
  33.  
  34. rollback
  35.  
  36. begin tran
  37.  
  38. declare @row int, @last varchar(20), @current varchar(20)
  39. set @last = ''
  40. declare dupes cursor
  41. for
  42. select val
  43. from test
  44. where val in ( -- only return values that are duplicated
  45. select val
  46. from test
  47. group by val
  48. having count(val)>1
  49. )
  50. order by val
  51.  
  52. for update of val
  53.  
  54. open dupes
  55. fetch next from dupes into @current
  56. while @@fetch_status = 0
  57. begin
  58. --new set of dupes, like the partition by in the 2005 example
  59. if @last != @current
  60. set @row = 1
  61.  
  62. update test
  63. --@last is being set during the update statement
  64. set val = val + ltrim(str(@row)), @last = val
  65. where current of dupes
  66.  
  67. set @row = @row + 1
  68.  
  69. fetch next from dupes into @current
  70. end
  71. close dupes
  72. deallocate dupes
  73.  
  74. select * from test
  75.  
  76. rollback
  77.  
  78. update mytable set mycolumn = concat(mycolumn, id)
  79. where id in (<select duplicate records>);
  80.  
  81. ALTER TABLE <table_name> ENABLE NOVALIDATE UNIQUE;
Add Comment
Please, Sign In to add comment