简体   繁体   中英

How to pass the returned value of SELECT statement to DELETE query in stored procedure?

I have the requirement to delete the child data's(foreign key constraints mapped) of some tables in DB. So, actually, i wanna to pass the value of returned SELECT query into the DELETE statement.

Following is the Stored Procedure i have created,pls help me to know about this and also give some examples to delete the child rows from table.

delimiter //
create procedure deleteCustomerDeps(in emailAddr varchar(50)) 
begin 
select customer_id into custId
from customer
where customer_id=emailAddr;
set @custoId=custId;
delete from customer where customer_id='@custoId';
prepare stmt from @custoId;
execute stmt;
deallocate prepare stmt;
end //
delimiter ;

TIA....

Let's suppose you have the following schema

CREATE TABLE customers
(
  customer_id INT, 
  customer_email VARCHAR(17),
  PRIMARY KEY (customer_id)
);
CREATE TABLE child_table
(
  child_id INT,
  customer_id INT, 
  value INT,
  PRIMARY KEY (child_id),
  FOREIGN KEY (customer_id) REFERENCES customers (customer_id)
);

Now to delete all child records knowing an email of the customer you can use multi-table delete syntax

CREATE PROCEDURE deleteCustomerData(IN emailAddr VARCHAR(50)) 
  DELETE t
    FROM child_table t JOIN customers c 
      ON t.customer_id = c.customer_id
   WHERE c.customer_email = emailAddr;

Here is SQLFiddle demo


...but if i want to pass the returned value of SELECT stmt to DELETE...

That is exactly what you're doing in above mentioned example. But you can always rewrite it this way

DELETE t
  FROM child_table t JOIN 
(
  SELECT customer_id 
    FROM customers JOIN ...
   WHERE customer_email = emailAddr
     AND ...
) c
    ON t.customer_id = c.customer_id

or

DELETE 
  FROM child_table 
 WHERE customer_id IN 
(
  SELECT customer_id 
    FROM customers JOIN ...
   WHERE customer_email = emailAddr
     AND ...
) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM