Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
rudba
Constraint Violating Yak Guru
415 Posts |
Posted - 2009-04-17 : 12:45:31
|
| Why i can not update the duplicate records?the output will be dup='Y' for Id: 1, and 2declare @tbl1 table (ID INT,Dup nvarchar(1))INSERT INTO @tbl1SELECT 1, 'Y'INSERT INTO @tbl1SELECT 1, nullINSERT INTO @tbl1SELECT 1, nullINSERT INTO @tbl1SELECT 2, 'Y'INSERT INTO @tbl1SELECT 2, nullINSERT INTO @tbl1SELECT 2, nullINSERT INTO @tbl1SELECT 3, nullINSERT INTO @tbl1SELECT 4, nullUPDATE a SET a.Dup = 'Y'FROM ( SELECT ID FROM @tbl1 WHERE Dup = 'Y' Group By ID ) djoin @tbl1 a on a.ID = d.IDWHERE a.Dup!= 'Y'select ID,Dup from @tbl1 |
|
|
vijayisonly
Master Smack Fu Yak Hacker
1836 Posts |
Posted - 2009-04-17 : 13:15:57
|
| may be u need this?UPDATE a SET a.Dup = 'Y'FROM (SELECT ID,count(ID) as cntFROM @tbl1Group By ID) djoin @tbl1 aon a.ID = d.IDWHERE d.cnt > 1 |
 |
|
|
rudba
Constraint Violating Yak Guru
415 Posts |
Posted - 2009-04-17 : 13:34:35
|
| thank vijayisonly,if i have more data, it will update Id =4 too.declare @tbl1 table (ID INT,Dup nvarchar(1))INSERT INTO @tbl1SELECT 1, 'Y'INSERT INTO @tbl1SELECT 1, nullINSERT INTO @tbl1SELECT 1, nullINSERT INTO @tbl1SELECT 2, 'Y'INSERT INTO @tbl1SELECT 2, nullINSERT INTO @tbl1SELECT 2, nullINSERT INTO @tbl1SELECT 3, nullINSERT INTO @tbl1SELECT 4, nullINSERT INTO @tbl1SELECT 4, nullINSERT INTO @tbl1SELECT 4, nullINSERT INTO @tbl1SELECT 4, nullUPDATE a SET a.Dup = 'Y'FROM (SELECT ID,count(ID) as cntFROM @tbl1Group By ID) djoin @tbl1 aon a.ID = d.IDWHERE d.cnt > 1select ID,Dup from @tbl1 |
 |
|
|
vijayisonly
Master Smack Fu Yak Hacker
1836 Posts |
Posted - 2009-04-17 : 13:36:43
|
| If you have 3 records for ID = 4 ....Isn't that considered duplicate?Are you saying we should be updating only if Dup = 'Y' for one of the rows?If that is the case...try thisUPDATE a SET a.Dup = 'Y'FROM (SELECT ID,DupFROM @tbl1where Dup = 'Y') djoin @tbl1 aon a.ID = d.ID |
 |
|
|
Lamprey
Master Smack Fu Yak Hacker
4614 Posts |
Posted - 2009-04-17 : 13:49:54
|
Another alternative:UPDATE @tbl1SET Dup = 'Y'WHERE ID IN (SELECT DISTINCT ID FROM @tbl1 WHERE Dup = 'Y') |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2009-04-17 : 13:55:58
|
| [code]UPDATE tSET t.Dup='Y'FROM @tbl1 tJOIN (SELECT ID FROM @tbl1 GROUP BY ID HAVING COUNT(CASE WHEN Dup='Y' THEN 1 ELSE 0 END) >0 ) t1ON t1.ID=t.IDWHERE t.Dup IS NULL[/code] |
 |
|
|
rudba
Constraint Violating Yak Guru
415 Posts |
Posted - 2009-04-17 : 15:12:53
|
| thanks guys,it works. |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2009-04-17 : 15:15:02
|
| welcome |
 |
|
|
|
|
|
|
|