简体   繁体   中英

MySQL Stored Procedure variables

In MySQL I'm trying to write a Stored Procedure which does the following:

  1. Run a SELECT query which returns 1 row with 2 columns (so two pieces of information).
  2. Run an INSERT query which includes the two previous values returned and a few parameters which were passed into the stored procedure.

I was originally thinking I could store the two pieces of information from Step 1 into a variable, and then pass those into Step 2. After some reading though it seems that a variable in MySQL can only hold 1 piece of data. How can I get the 2 pieces of information from Step 1 into my INSERT statement in Step 2?

Thank you!

You can use INSERT INTO ... SELECT . Example,

INSERT INTO table1 
SELECT col1, 
       col2, 
       value1, 
       value2 
FROM   table2 

Here you select col1 , col2 from table2 and add 2 new custom values value1 and value2 to the result set. This new 4 columns get inserted in to the table1

You can use SELECT ... INTO clause, which will select values from specified table to variables you define in stored proc.

Refer to manual: http://dev.mysql.com/doc/refman/5.0/en/select-into.html

create something like this:

CREATE PROCEDURE InsertThis(IN paramA varchar(50), IN paramB int, INT paramC varchar(50))
BEGIN
     INTO INTO tableB(fieldA, fieldB, fieldC, fieldD)
     SELECT paramA as fieldA, paramB as fieldB, fieldC, fieldD
     FROM tableA
     WHERE fieldC = paramC;
END

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