I have one table called ServiceCodes in that havings Columns like Customer, companyId, ServiceCode, CompanySourc, NewlyInserted. I have to insert some records into this table. On that time I am inserting same customer and serviceCode values into that table. On that item I am updating this NewlyInserted bit into 1. By using this is there any way to get those Duplicated rows? And after that I want to remove those duplicated rows. In SSMS SQL example in ServiceCodes table
custID1,compid1,Service1233,CompSource1,0
custID2,compid1,Service1234,CompSource1,0
custID3,compid1,Service1235,CompSource1,0
custID4,compid1,Service1236,CompSource1,0
custID3,compid1,Service1235,CompSource1,1
custID4,compid1,Service1236,CompSource1,1
How to find these two rows servicecode and CustId combination are already there in that ServiceCodes table? I have tried Inner Join
and Cross apply
and all, it is not working for me.
EDIT:
UPDATE Servicecodes
SET isNeedstobeDelete = 1
FROM Servicecodes
CROSS APPLY (SELECT distinct Client,ServiceCode FROM Servicecodes WHERE NewlyInserted = 0) AS ApplicableClients
WHERE
NewlyInserted = 1
AND [Servicecodes].Client= [ApplicableClients].Client
AND NOT EXISTS (SELECT 1 FROM @tempservicecodes
WHERE [Servicecodes].servicecode = [ApplicableClients].servicecode
AND [Servicecodes].clientid = [ApplicableClients].clientid)
delete from servicecodes where isNeedstobeDelete = 1
it is taking so much time to run when data size is getting increased , so please give a solution which will take less amount of time ,please consider this aspect as well.
and there is no other conditions we have in this table. this deletion will occur every time user cicks one button.
3条答案
按热度按时间mgdq6dx11#
You can use a subquery to check for duplicates. SQL Server supports a
delete t1 from table1 as t1
syntax where you can assign an alias to the table you want to delete from:Example at DBFiddle.
vof42yt12#
A solution that uses the
ROW_NUMBER()
window function to search for duplicates.Try it on db<>fiddle .
Update:
If you need to "delete" and "update", then you need the
MERGE
statement (all aboutOUTPUT
clause).Try it on db<>fiddle .
xmq68pz93#
Somehow, I Found this Left JOIN It is working Fine and Performance also Pretty Good.