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.
Author |
Topic |
cblatchford
Starting Member
40 Posts |
Posted - 2006-09-05 : 06:38:54
|
Hi all,I have two tables, the second of which reference the first via an ID code. I'd like to setup a trigger on table1 that, when a delete is performed on table1, the trigger performs a delete on table2' record with the same ID code. For example..Table1IDCode123361367Table2IDCode123361367So when record 123 is deleted out of table1, the same record in table2 is deleted. Would it be along the lines of..Delete from table2inner join table1on table1.idcode = table2.idcodeThanks Blatch. |
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2006-09-05 : 07:08:01
|
The code above would delete all records that DOES exist.DELETE t2FROM Table2 t2WHERE t2.IdCode NOT IN (SELECT t1.IdCode FROM Table1 t1) OrDELETE t2FROM Table2 t2LEFT JOIN Table1 t1 ON t1.IdCode = t2.IdCodeWHERE t1.IdCode IS NULL Peter LarssonHelsingborg, Sweden |
 |
|
harsh_athalye
Master Smack Fu Yak Hacker
5581 Posts |
Posted - 2006-09-05 : 07:09:14
|
It will be like...Delete Table2from table2 inner join table1on table1.idcode = table2.idcode because SQL server needs to understand the table from which the data to be deleted. Why don't you go for CASCADE DELETE option, provided there is foreign key relationship between these two tables? Harsh AthalyeIndia."Nothing is Impossible" |
 |
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2006-09-05 : 07:13:12
|
That would also delete all existing rows that have match.With a trigger, useDELETE t2FROM Table2 t2WHERE t2.IdCode IN (SELECT d.IdCode FROM deleted d) Peter LarssonHelsingborg, Sweden |
 |
|
cblatchford
Starting Member
40 Posts |
Posted - 2006-09-05 : 07:19:07
|
Thanks both; there is a foreign key constraint but I've gone with Peso first option..tablatch |
 |
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2006-09-05 : 07:56:43
|
If you really consider a trigger,DELETE t2FROM Table2 t2WHERE t2.IdCode IN (SELECT d.IdCode FROM deleted d) is the best option.Peter LarssonHelsingborg, Sweden |
 |
|
chiragkhabaria
Master Smack Fu Yak Hacker
1907 Posts |
Posted - 2006-09-05 : 08:22:26
|
How about using Cascade delete ???Chirag |
 |
|
harsh_athalye
Master Smack Fu Yak Hacker
5581 Posts |
Posted - 2006-09-05 : 08:32:07
|
quote: Originally posted by chiragkhabaria How about using Cascade delete ???Chirag
It's amazing to find two professionals thinking along the same way ! Harsh AthalyeIndia."Nothing is Impossible" |
 |
|
|
|
|