My SQL 动态查询执行并将输出输出到存储过程中的变量中
Posted
技术标签:
【中文标题】My SQL 动态查询执行并将输出输出到存储过程中的变量中【英文标题】:My SQL Dynamic query execute and get ouput into a variable in stored procedure 【发布时间】:2011-08-01 06:30:32 【问题描述】:我在 My sql 存储过程中生成了一个动态查询。我想将此查询的结果放入 out 参数中。如何做到这一点?
CREATE PROCEDURE 'searchInvoice'
(
OUT numOfRecords INT
)
BEGIN
DECLARE query1 TEXT;
DECLARE query2 TEXT;
SET query1 = 'SELECT COUNT(*) bla bla bla.....';
// Query1 to select the count of matching tuples..
SET query2 = 'SELECT * from bla bla bla....';
// Query2 to select original records...
// later part of this both queries generate dynamically according to some IN parameters..
// now I wanna assign the output of the query1 into numOfRecords
// and I wanna execute the query2 as well.. like this
SET @Sql = query2;
PREPARE STMT FROM @Sql;
EXECUTE STMT;
DEALLOCATE PREPARE STMT;
// output of the query2 can be read in php
END
如何将 query1 的输出转换为 OUT 参数(numOfRecords
) ??
【问题讨论】:
【参考方案1】:看看这个例子 -
CREATE TABLE table1(
column1 VARCHAR(255) DEFAULT NULL,
column2 VARCHAR(255) DEFAULT NULL,
column3 VARCHAR(255) DEFAULT NULL
);
INSERT INTO table1 VALUES
('1', 'value1', 'value2'),
('2', 'value3', 'value4');
DELIMITER $$
CREATE PROCEDURE procedure1(IN Param1 VARCHAR(255), OUT Param2 VARCHAR(255), OUT Param3 VARCHAR(255))
BEGIN
SET @c2 = '';
SET @c3 = '';
SET @query = 'SELECT column2, column3 INTO @c2, @c3 FROM table1 WHERE column1 = ?';
PREPARE stmt FROM @query;
SET @c1 = Param1;
EXECUTE stmt USING @c1;
DEALLOCATE PREPARE stmt;
SET Param2 = @c2;
SET Param3 = @c3;
END$$
DELIMITER ;
-- Call procedure and use variables
SET @Param1 = 2;
SET @Param2 = '';
SET @Param3 = '';
CALL procedure1(@Param1, @Param2, @Param3);
SELECT @Param2, @Param3;
+---------+---------+
| @Param2 | @Param3 |
+---------+---------+
| value3 | value4 |
+---------+---------+
【讨论】:
@Devart 如果获取多条记录,如何存储在临时表中?【参考方案2】:select count(*) into @numOfRecords from ....
你必须在存储过程中声明变量
希望我已经理解了你的问题。
【讨论】:
以上是关于My SQL 动态查询执行并将输出输出到存储过程中的变量中的主要内容,如果未能解决你的问题,请参考以下文章