Avatar of johnkainn
johnkainn
 asked on

Delete - when no rows

I have 2 tables.  GTable (GId, GText)   CTable (CId, GId, CText)
I would like to delete row from GTable when there are no rows in CTable that refer to GTable.
For example. If there are 2 rows in CTable with GId=4 no action.
But if there are 0 rows with GId=5 I would like to delete from GTable the row GId=5.
How is best to do this?
Microsoft SQL Server 2008

Avatar of undefined
Last Comment
anillucky31

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
tigin44

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
anillucky31

I am assuming that you will supply GID as input to delete

declare @GID int

set @GID = 3  -- Or your inputed value

delete from GTable where GId = @GID and not exists(select 1 from CTable where GId = @GID)

delete from GTable where GId = @GID and not exists(select 1 from CTable where GId = @GID)


--if you want to delete full table then use this command

delete from GTable where GId not in (select GID from CTable)
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck