[英]Can't execute a MySQL SELECT statement when inside CONCAT
I have been trying to create a simple loop of SELECT statements in MySQL to reduce code. 我一直试图在MySQL中创建一个SELECT语句的简单循环以减少代码。 I have started this using
CONCAT()
however this causes the procedure to stop/fail. 我已经使用
CONCAT()
启动了它,但是这导致程序停止/失败。 For example (where k is a loop counter): 例如(其中k是循环计数器):
CONCAT('SELECT (Child_', k, ' INTO @Age_Child_', k, ' FROM lookup_childage WHERE ModYear = ModYear_var LIMIT 1)');
To diagnose the issue, I simply tried to place the SELECT statement (without concatenated loop variables) inside a string to then be executed. 为了诊断问题,我只是尝试将SELECT语句(没有串联的循环变量)放在一个字符串中然后执行。 While I could get this to work for simple statements it would not work for the following:
虽然我可以将其用于简单的语句,但不适用于以下情况:
SET @queryString = CONCAT('SELECT Child_1 INTO @Age_Child_1 FROM lookup_childage WHERE ModYear = ModYear_var LIMIT 1');
PREPARE stmt FROM @queryString;
EXECUTE stmt;
Does anyone know why the @queryString
containing the CONCAT()
statement will not be executed/cause the procedure to fail? 有谁知道为什么包含
CONCAT()
语句的@queryString
不会被执行/导致过程失败?
tl;dr The statement you're trying to write has the form SELECT(rest of statement) LIMIT 1
. tl; dr您要编写
SELECT(rest of statement) LIMIT 1
的形式为SELECT(rest of statement) LIMIT 1
。 It should have the form SELECT rest of statement LIMIT 1
. 它的形式应为
SELECT rest of statement LIMIT 1
。
It looks like you want to create variable column names, ummm, because your lookup_childage
table is denormalized. 看起来您想创建变量列名称ummm,因为
lookup_childage
表已被非规范化。 I guess that table has these columns. 我猜该表有这些列。
Child_1 INT
Child_2 INT
Child_3 INT
Child_4 INT
It looks like you hope to get a @queryString
value containing this sort of thing: 看来您希望获取包含此类内容的
@queryString
值:
SELECT Child_4 INTO @Age_Child_4 FROM lookup_childage WHERE ModYear = ModYear_var LIMIT 1
Only the 4
s are variable. 只有
4
s是变量。
So to get that string you want 所以要得到你想要的字符串
SELECT CONCAT('SELECT Child_', k,
' INTO @Age_Child_', k,
' FROM lookup_childage WHERE ModYear = ModYear_var LIMIT 1'
)
INTO @queryString;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.