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.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 delete data from multiple tables

Author  Topic 

rudba
Constraint Violating Yak Guru

415 Posts

Posted - 2010-04-01 : 15:00:14
Is there a way to delete data from multiple tables in a single query?

I want to delete @tbl1 and @tbl2 where StudentID=101
declare @tbl1 table(
StudentID int,
fname varchar(10))

INSERT INTO @tbl1
SELECT 101, 'AA'

INSERT INTO @tbl1
SELECT 102,'BB'

declare @tbl2 table(
ID int,
StudentID int)
INSERT INTO @tbl2
SELECT 1, 101

INSERT INTO @tbl2
SELECT 2,102

INSERT INTO @tbl2
SELECT 3, 102

INSERT INTO @tbl2
SELECT 4,101

select * from @tbl1
select * from @tbl2

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2010-04-01 : 15:08:21
You might be able to using the MERGE statement (I know you can insert into two at once). Since you are a "Constraint Violating Yak Guru," you should give it a try! :)

EDIT: Thought I was in a 2008 forum.. I guess you can't since MERGE is 2008.

But, my question is why would you need/want to do that?
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2010-04-01 : 17:01:48
If they are related and you are using cascading foreign keys, then SQL Server will handle the child tables for you. But other than that, you'll need to use one DELETE statement per table in SQL Server 2005.

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page

rudba
Constraint Violating Yak Guru

415 Posts

Posted - 2010-04-01 : 17:12:40
they are related but there is not set foreign keys.
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2010-04-01 : 17:14:57
Why not? That's a very bad design if you don't have foreign keys. They are used to protect data from bad programmers.

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page
   

- Advertisement -