简体   繁体   English

运行保存在字段中的SQL查询

[英]Run SQL query saved in a field

I have a follow up question on the link below. 我在下面的链接中有一个后续问题。 Apparently I have to create a new question (Sorry if I should not, I am new to stackoverflow) 显然我必须创建一个新问题(对不起,如果我不这样做,我是Stackoverflow的新手)

One of the responses to the issue was this: 对这个问题的回应之一是:

SELECT sql_text INTO @sql FROM sql_queries WHERE id = 1;
PREPARE sql_query FROM @sql;
EXECUTE sql_query;

It helped if I run the above line by line, but I want to run this as a whole and use the result in another query. 如果我逐行运行上面的命令,这很有帮助,但是我想整体运行它,并在另一个查询中使用结果。 So my issue is the following: 所以我的问题是:

1 - It doesn't work if I remove the semicolons and try to run the three lines at the same time. 1-如果我删除分号并尝试同时运行三行,则不起作用。

2 - How can I read the results of this run into a query. 2-如何读取运行查询的结果。 I was thinking of putting all three lines in a subquery, but that didn't work. 我当时正在考虑将所有三行都放在一个子查询中,但这没有用。

I appreciate if you have any comment on those. 如果您对此有任何评论,不胜感激。 Thanks! 谢谢!

OriginalQuestion OriginalQuestion

I do not think you can "embed" an execute (nor it's results) in another query, which is what it sounds like what your goal is. 我认为您不能在另一个查询中“嵌入”执行(也不是结果),这听起来像是您的目标。 Instead you might want to consider building your final query with the @sql query as a subquery like: 相反,您可能需要考虑使用@sql查询作为子查询来构建最终查询,例如:

SET @finalSQL = CONCAT("SELECT stuff FROM sometables JOIN (", @sql, ") AS subQ ON blah");
PREPARE sql_query FROM @sql;
EXECUTE sql_query;

Of course, you need to make a lot of assumptions about the @sql query you've been provided; 当然,您需要对已提供的@sql查询做出很多假设 at minimum you must assume: it will be valid for the join conditions (or however the subquery is used) and that it is not terminated with a semi-colon. 至少您必须假定:它对连接条件有效(或使用子查询),并且它不以分号终止。 The latter can be easily checked and remedied, the former could require a significant amount of parsing and analysis. 后者很容易检查和修复,前者可能需要大量的分析和分析。

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

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