简体   繁体   English

在另一个存储过程中获取存储过程结果集

[英]Get stored procedure resultset inside another stored procedure

Let's say I have multiples stored procedures that uses the same subquery in IN clauses.假设我有多个在 IN 子句中使用相同子查询的存储过程。 The subquery select a list of IDs.子查询 select 是一个 ID 列表。 My reflex was to go a ahead and create a new stored procedure containing this subquery to define it in a single place, and use it inside the others procedures.我的反应是提前 go 并创建一个包含此子查询的新存储过程以在一个地方定义它,并在其他过程中使用它。 Now I realize that I cannot get the resultset from the subquery when calling the stored procedure... I searched and found no alternatives other than defining a temporary table, which I found overkill to get a couples Ids.现在我意识到在调用存储过程时我无法从子查询中获取结果集......我搜索并发现除了定义一个临时表之外没有其他选择,我发现获得一对 Id 有点过头了。 Is there something I'm missing or I simply cannot do this in MYSQL?有什么我遗漏的,或者我根本无法在 MYSQL 中做到这一点?

To illustrate my problem:为了说明我的问题:

CREATE PROCEDURE subquery()
BEGIN   
    SELECT id from example; # returns a list of IDs
END;

CREATE PROCEDURE procedure1()
BEGIN   
    SELECT * from example2 WHERE id IN (CALL subquery()); # No go, syntax error
END;

CREATE PROCEDURE procedure2()
BEGIN
    SET @resultSet = CALL subquery();
    SELECT * from example2 WHERE id IN (@resultSet); # No go, syntax error
END;

Of course the real subquery is a big chunk of SQL that I prefer to maintain in a single place.当然,真正的子查询是 SQL 的一大块,我更喜欢将其维护在一个地方。

As I understand it, I can't use Functions as they only returns scalars values, and I can't use OUT parameters as they don't allow resultsets.据我了解,我不能使用函数,因为它们只返回标量值,我不能使用 OUT 参数,因为它们不允许结果集。

What are my alternatives here other than multiplying subqueries or using temporary table as defined here ?除了乘以子查询或使用此处定义的临时表之外,我还有什么选择?

Unfotunatelly you cannot use a stored procedure output inside another stored procedure in MySQL.不幸的是,您不能在 MySQL 的另一个存储过程中使用存储过程 output。 But if your subquery does not require parameters the best option (in my opinion) is a VIEW:但是,如果您的子查询不需要参数,最好的选择(在我看来)是 VIEW:

CREATE VIEW myView AS select id from example;

and then you can reference your view as a table (inside other stored procs as well):然后您可以将您的视图引用为表格(也在其他存储的过程中):

SELECT * from example2 WHERE id IN (select id from myView);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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