SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 delete rows from table
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

eugz
Posting Yak Master

195 Posts

Posted - 03/01/2013 :  10:41:20  Show Profile  Reply with Quote
Hi All

I have two tables. The Table1 has Req_Id like primery key and Table2 has Req_Id like foreign key. And I would like delete rows from Table2 where same Req_Id doesn't exists in Table1. I create SELECT to retrive such records. My select is

select *
from dbo.Table2
where Req_Id not in (select Req_Id from dbo.Table1)

How to delete those records?

Thanks.

MIK_2008
Flowing Fount of Yak Knowledge

Pakistan
1054 Posts

Posted - 03/01/2013 :  10:58:24  Show Profile  Reply with Quote
DELETE
from dbo.Table2
where Req_Id not in (select Req_Id from dbo.Table1)

Cheers
MIK
Go to Top of Page

eugz
Posting Yak Master

195 Posts

Posted - 03/01/2013 :  12:07:55  Show Profile  Reply with Quote
Hi MIK. Thanks for replay.

How to modify your code if I would like delete just one record? For instance, if Table2 has Req_Id=2 and Table1 doesn't has Req_Id=2.

Thanks.

Go to Top of Page

James K
Flowing Fount of Yak Knowledge

3744 Posts

Posted - 03/01/2013 :  12:19:31  Show Profile  Reply with Quote
If you know the ID you want to delete, you don't need to involve Table1
DELETE FROM TABLE2 WHERE Req_ID = 2
If you want to select the qualifying rows and delete just one of those, use this:
;WITH cte AS
(
	SELECT TOP (1) * FROM dbo.Table2 t2
	WHERE NOT EXISTS 
	(
		SELECT 1 FROM dbo.Table1 t1 WHERE t1.Req_Id = t2.Req_id
	)
) DELETE FROM cte;
I am assuming that logically there should be a foreign key relationship, but there is no such constraint in the database. If there was, this situation should not have come about in the first place.
Go to Top of Page

eugz
Posting Yak Master

195 Posts

Posted - 03/01/2013 :  14:24:12  Show Profile  Reply with Quote
Hi James. Thanks.
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.05 seconds. Powered By: Snitz Forums 2000