[英]Process Multiple Row by a MYSQL Store Procedure
I am facing some trouble inserting data into a table by Store Procedure. 我在使用Store Procedure将数据插入表时遇到了一些麻烦。 Please allow me to explain in details. 请允许我详细解释一下。
I have a Three tables 我有一张三张桌子
CREATE TABLE `table_1` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`s_id` INT(11) NOT NULL,
`created` DATE NOT NULL,
`val` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
AUTO_INCREMENT=1;
CREATE TABLE `table_2` (
`s_id` INT(11) NOT NULL AUTO_INCREMENT,
`t_id` INT(11) NOT NULL,
`p_id` INT(11) NOT NULL,
`d_id` INT(11) NOT NULL,
`created` DATE NOT NULL,
PRIMARY KEY (`id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
AUTO_INCREMENT=1;
CREATE TABLE `table_3` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`count` INT(11) NOT NULL,
`created` DATE NOT NULL,
`s_id` VARCHAR(255) NOT NULL,
`t_id` VARCHAR(255) NOT NULL,
`p_id` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`)
)
Is there any way to insert into 2nd table by store procedure using select statement. 有没有办法使用select语句通过存储过程插入第二个表。 There will be multiple data as Select * from table_1
; Select * from table_1
会有多个数据; Then there will be a process like if(table_1.s_id == table_3.s_id) THEN UPDATE table_3 set count = count +1 ELSE INSERT into table_3
(s_id,t_id..... 然后会有一个像if(table_1.s_id == table_3.s_id) THEN UPDATE table_3 set count = count +1 ELSE INSERT into table_3
那样的进程if(table_1.s_id == table_3.s_id) THEN UPDATE table_3 set count = count +1 ELSE INSERT into table_3
(s_id,t_id .....
Though I have tried using Cursor but its inserting only one record. 虽然我已经尝试使用Cursor但它只插入一条记录。
Here are the example of my usage of Cursor 以下是我使用Cursor的示例
DECLARE done INT DEFAULT FALSE;
DECLARE curs_count INT(11) DEFAULT 0;
DECLARE v_s_id BIGINT(20) DEFAULT 0;
DECLARE v_t_id BIGINT(20) DEFAULT 0;
DECLARE v_p_id BIGINT(20) DEFAULT 0;
DECLARE v_t_date BIGINT(20) DEFAULT 0;
DECLARE co_s_id BIGINT(20) DEFAULT 0;
DECLARE curs CURSOR FOR
SELECT
a.id,b.s_id,b.t_id,b.created
FROM
table_1 a
INNER JOIN table_2 b ON a.s_id = b.s_id
WHERE
a.val <> '';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
DECLARE curs_id INT(11) DEFAULT 0;
OPEN curs;
SELECT FOUND_ROWS() INTO curs_count;
start_loop: loop
FETCH curs INTO curs_id,v_s_id,v_t_id,v_c_date;
IF done THEN
LEAVE start_loop;
END IF;
SELECT s_id INTO co_s_id FROM table_3;
IF co_s_id>0
THEN
update table_3 SET count = count+1 where s_id = co_s_id;
ELSE
INSERT INTO table_3 (support_id,track_id,track_date,count) VALUES (v_s_id,v_t_id,v_c_date,1);
END IF;
end loop;
CLOSE curs;
Can anyone help me out with this? 任何人都可以帮我解决这个问题吗?
This code is running properly. 此代码正常运行。 The issue was infinite loop made the tables corrupted so no data were inserting. 问题是无限循环使表损坏,因此没有数据插入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.