简体   繁体   English

在select语句中使用存储过程的结果[MySql]

[英]Use results of a stored procedure in a select statement [MySql]

I have a stored procedure which returns several values (1 row). 我有一个存储过程,它返回几个值(1行)。 I need to use the results of that stored procedure in a select query. 我需要在select查询中使用该存储过程的结果。

Here is pseudo-code of how I would like it to be (such syntax does not exist, but let's pretend it would allow to save 3 values, which my stored procedure returns, into C, D and E): 下面是我希望它的伪代码(这样的语法不存在,但让我们假设它允许将我的存储过程返回的3个值保存到C,D和E中):

SELECT
  t1.A, t1.B,
  MyStoredProc(t1.A) AS (C, D, E)
FROM
  t1
ORDER BY
  D
LIMIT
  1

(on the client side I need to get A, B, C, D and E) (在客户端我需要获得A,B,C,D和E)

I can rewrite the stored procedure to a stored function which returns values as a concatenated string with delimiters and parse out the values in the query, but I would like to find a cleaner solution. 我可以将存储过程重写为存储函数,该函数将值作为带有分隔符的连接字符串返回并解析查询中的值,但我想找到一个更清晰的解决方案。

You can't access the values from a result-set returned by a stored procedure within another query. 您无法从另一个查询中的存储过程返回的结果集中访问这些值。 They are only sent to the client. 它们只发送给客户。 The result-set looks like a table, but it is not a table. 结果集看起来像一个表,但它不是表。

There is, however, a workaround, described here: 但是,有一个解决方法,如下所述:

How to use Table output from stored MYSQL Procedure 如何使用存储的MYSQL过程中的表输出

It doesn't get you precisely where you need to go, but it gets you as close as you can get. 它无法准确地将您带到您需要去的地方,但它可以让您尽可能接近。

Otherwise, you can write three stored functions all run the exact same bit of logic, but which cache their results in session variables so whichever function executes first will set things up for the other two so they complicated logic only executes once for a given input value and then re-executes for the next input value since it's different than the one cached. 否则,您可以编写三个存储的函数,它们都运行完全相同的逻辑位,但是将它们的结果缓存在会话变量中,因此无论哪个函数首先执行都将为其他两个函数设置,因此它们复杂的逻辑只对给定的输入值执行一次然后重新执行下一个输入值,因为它与缓存的输入值不同。

IF NOT @__cached__function_input <=> input_arg THEN
  SET @__cached__function_input = input_arg;
  SELECT complicated, logic, things INTO @__cached__a, @__cached__b, @__cached__c;
END IF;

RETURN @__cached__a; # in function "a" -- return b in b and c in c

If you use unique variable names for any given function, these won't collide. 如果对任何给定函数使用唯一变量名,则这些名称不会发生冲突。 Functions are executed serially, not in parallel, even for data on the same row of a statement that returns multiple rows. 即使对于返回多行的语句的同一行上的数据,函数也是串行执行的,而不是并行执行的。

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

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