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 |
sg2255551
Constraint Violating Yak Guru
274 Posts |
Posted - 2014-05-27 : 04:41:31
|
hiSorry,in order to avoid spam. I have deleted the previous post.Here is my code and table sample. In the 5th and 6th row of Table C are actually the duplicate of 1st and 2nd row which i want to avoid. How should i rewrite the SQL to avoid duplicate insertion? Thanks a lot.Select @ID = Max(ID) + 1 from TableCWith Cte as(Select distinct TableB.ProdID TableB where TableB.ProdGroupId = @GroupID)Insert into [dbo].[TableC]([ID] ,[TEXT], [ProdGroupId])Select @ID, @Text, TableB.ProdGroupId from TableB INNER JOIN CTEON TableB.SupplierProdID = Cte.ProdIDwhere TableB.ProdID = @ProdIDTable C1 A1 Grp12 A2 Grp22 A3 Grp13 A4 Grp23 A1 Grp14 A2 Grp2 |
|
sunder.bugatha
Yak Posting Veteran
66 Posts |
Posted - 2014-05-27 : 05:25:11
|
Insert into [dbo].[TableC]([TEXT], [ProdGroupId])Select distinct @Text, TableB.ProdGroupId from TableB INNER JOIN CTEON TableB.SupplierProdID = Cte.ProdIDwhere TableB.ProdID = @ProdIDupdate [TableC]set [ID] = @ID...your where logicHema Sunder |
|
|
gbritton
Master Smack Fu Yak Hacker
2780 Posts |
Posted - 2014-05-27 : 08:41:30
|
I'd try this using merge. However, Since I don't know what's in TableB, I can't really work up an example for you. Could you please provide some data for Table B and your expected results. |
|
|
rocknpop
Posting Yak Master
201 Posts |
Posted - 2014-05-27 : 09:36:57
|
Can you try this:With Cte as(Select distinct TableB.ProdID TableB where TableB.ProdGroupId = @GroupID),CTE2AS( Select @Text AS [Text], TableB.ProdGroupId, ROW_NUMBER()OVER(PARTITION BY @Text, TableB.ProdGroupId ORDER BY TableB.ProdGroupId) AS ROWNUM from TableB INNER JOIN CTE ON TableB.SupplierProdID = Cte.ProdID where TableB.ProdID = @ProdID)Insert into [dbo].[TableC]([ID] ,[TEXT], [ProdGroupId])Select @ID, [Text], ProdGroupId FROM CTE2where ROWNUM=1--------------------Rock n Roll with SQL |
|
|
Lamprey
Master Smack Fu Yak Hacker
4614 Posts |
Posted - 2014-05-27 : 11:36:36
|
Put a Unique Constraint on those two columns.http://technet.microsoft.com/en-us/library/ms189862(v=sql.105).aspxEDIT: Opps I mis-read what you wanted. Please ignore. |
|
|
sg2255551
Constraint Violating Yak Guru
274 Posts |
Posted - 2014-05-30 : 05:45:18
|
Thanks everybody. Been busy and did not have time to reply. I used this to delete duplicate. Thanks a lot.with cte as( select row_number() over (partition by Prod_ID, ProdName order by ID desc) as rn from prodduct where Prod_ID = @Prod_ID)delete from cte where rn > 1 |
|
|
gbritton
Master Smack Fu Yak Hacker
2780 Posts |
Posted - 2014-05-30 : 07:38:52
|
better to avoid inserting the duplicate in the first place! |
|
|
|
|
|
|
|