0

I have 2 tables:

  • FirstTable
  • SecondTable

FirstTable has these columns

sales_ID varchar(250)
product_ID int

SecondTable has these columns

sales_ID varchar(250)
product_ID int
CreateDate datetime

If FirstTable's sales_ID and product_ID match to SecondTable's sales_Id and product_ID, and also if SecondTable's CreatedDate is 07.04.2015, I need to delete the row from SecondTable

I tried like this:

delete from SecondTable
WHERE sales_Id IN (SELECT sales_Id FROM FirstTable) 
  and product_ID IN (SELECT product_ID FROM FirstTable) 
  and CreatedDate = '07-04-2015'

However it deletes all rows and also it is not correct (not working) query according to what I want.

How can I delete duplicate rows if product_ID equals product_ID and sales_ID equal sales_ID and CreatedDate equals 07.04.2015 from SecondTable?

Hope you understand my bad english

Thanks.

3 Answers 3

3

That's because it's purely checking for the presence of the sales id in the second table and the product id, seperately, not on the same record.

Try for example

Delete T2
FROM firsttable AS T1
INNER JOIN secondtable T2
on T1.sales_id = T2.sales_id
AND T1.product_id = T2.product_id
WHERE T1.CreatedDate = '20150407'  -- assuming you mean 7th April?
Sign up to request clarification or add additional context in comments.

Comments

1

try this:

delete from secondtable
from secondTable st
inner join firstTable ft on st.sales_id = ft.sales_id
    and st.product_id = ft.product_id
    and st.CreatedDate = '2015-07-04'

note you'll probably want to wrap the above in a transaction to make sure you're not deleting unwanted records - or turn the statement into a select:

select st.*
from secondTable st
inner join firstTable ft on st.sales_id = ft.sales_id
    and st.product_id = ft.product_id
    and st.CreatedDate = '2015-07-04'

Comments

1
DELETE 
  FROM SecondTable t2
  JOIN FirstTable t1
    ON t1.sales_ID = t2.sales_ID
   AND t1.product_ID = t2.product_ID
   AND t1.CreatedDate = '2015-07-04'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.