I have been trying to create a simple loop of SELECT statements in MySQL to reduce code. I have started this using CONCAT()
however this causes the procedure to stop/fail. For example (where k is a loop counter):
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. 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?
tl;dr The statement you're trying to write has the form SELECT(rest of statement) LIMIT 1
. It should have the form SELECT rest of statement LIMIT 1
.
It looks like you want to create variable column names, ummm, because your lookup_childage
table is denormalized. 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:
SELECT Child_4 INTO @Age_Child_4 FROM lookup_childage WHERE ModYear = ModYear_var LIMIT 1
Only the 4
s are variable.
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.