Click here to Skip to main content
15,893,190 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
Table 1

OMID   ORDERNO
19     ORD-2222-REE
20     ORD-2223-REE

Table 2

ID  ORDERNOREF ITEM
1   19         A
2   20         B

This is my two table in sql.
In front i am selecting the ORDERNO from combo box.

Please tell me how to write the delete query to delete values from both the tables at a time.

Thank you
Posted
Comments
♥…ЯҠ…♥ 12-Nov-13 7:48am    
Which is parent table and child table?

It is not possible to delete reocrds from multiple tables at once. A DML statement can affect only one table.
You can do this by following statements.

SQL
DELETE 
FROM T2 
Inner JOIN T1 ON T2.ORDERNOREF = T1.OMID
Where T1.ORDERNO = @ORDERNO

DELETE FROM T1 Where ORDERNO = @ORDERNO.


You can use a stored procedure to execute these statements.
 
Share this answer
 
Have you tried anything? I'm guessing not.

Here are some tips rather than a complete solution.

Use the order number to find the OMID.
Delete from Table 2 where ORDERNOREF = OMID
Delete from Table 1 where OMID = OMID


Another option would be to define a relationship in SQL, so that when you delete from table 1 the delete cascades to table 2, in turn deleting the lines.

The third option, is a take on the first one where you

delete from table 2 where ORDERNOREF in (Select OMID from Table 1 where ORDERNO = your selected value)
delete from table 1 where ORDERNO = your selected value
 
Share this answer
 
try this
SQL
DELETE FROM TABLE_1 WHERE ORDERNOREF = 19;
DELETE FROM TABLE_2 WHERE OMID  = 19
 
Share this answer
 
v2
Try:
SQL
DELETE t1,t2 FROM Table1 t1 JOIN Table2 t2 ON t1.OMID=t2.ORDERNOREF WHERE t1.ORDERNO='ORD-2222-REE'
 
Share this answer
 
Comments
[no name] 12-Nov-13 7:53am    
Griff it's giving error saying "Invalid object near t1"
OriginalGriff 12-Nov-13 8:16am    
Sorry - That's MySql syntax, not MsSql - you can't do that in MsSql.
The best way would be to create a stored procedure to both deletes independently, inside a transaction so that if one fails, you can roll them both back - MsSql will not allow you to do multiple deletes in a single command (except cascade deletes) unfortunately.

Brain failure on my part - I need more coffee!
[no name] 12-Nov-13 23:14pm    
:)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900