[英]MySQL build a variable name?
I am trying to build a variable name dynamically within a user defined function but it seems it does not work. 我试图在用户定义的函数中动态构建变量名称,但似乎它不起作用。 Is there a way to do this or by using an array variable?
有没有办法做到这一点或使用数组变量?
I have a string of 7 characters which represents the days of the week (1234567, or 1_3_5_7, etc.). 我有一个7个字符的字符串,代表一周中的几天(1234567,或1_3_5_7等)。 I would like evaluate how often during a week a day is selected (from 0 to 7).
我想评估一周中一天选择的频率(从0到7)。 I thought, it would be easiest to use a loop to go through all the 7 positions but I get an error message saying
我想,最简单的方法是使用一个循环遍历所有7个位置,但是我收到一条错误信息
[Err] 1193 - Unknown system variable 'CONCAT'
[Err] 1193 - 未知的系统变量'CONCAT'
Any hints on how I can achieve that? 有关如何实现这一目标的任何提示? This is my code:
这是我的代码:
DELIMITER $$
DROP FUNCTION IF EXISTS fn_freq$$
CREATE FUNCTION fn_freq(days INT) RETURNS INT
BEGIN
DECLARE D1 VARCHAR(1);
DECLARE D2 VARCHAR(1);
DECLARE D3 VARCHAR(1);
DECLARE D4 VARCHAR(1);
DECLARE D5 VARCHAR(1);
DECLARE D6 VARCHAR(1);
DECLARE D7 VARCHAR(1);
DECLARE x INT;
DECLARE fn_freq INT;
SET x =1;
SET fn_freq = 0;
WHILE x < 8 DO
SET CONCAT('D',x) = MID(days, x, 1);
IF CONCAT('D',x) = '_' THEN
ELSE
SET fn_freq = fn_freq + 1;
SET x = x + 1;
END IF;
SET x = x + 1;
END WHILE;
RETURN fn_freq;
END$$
DELIMITER ;
You cant SET CONCAT as in SET CONCAT('D',x) = MID(days, x, 1)
what instead i think will be better to declare & set the concat value to that variable and use that variable for the IF condition. 你不能
SET CONCAT as in SET CONCAT('D',x) = MID(days, x, 1)
而是我认为更好地声明并将concat值设置为该变量并将该变量用于IF条件。 Also I think you missed out what have to be done in the case IF Condition is true. 另外我认为你错过了在IF条件为真的情况下必须做的事情。
Thanks for your reply. 感谢您的回复。 I got it to work like this, but I am still curious, how I could dynamically create a variable in some other cases.
我让它像这样工作,但我仍然很好奇,我可以在其他一些情况下动态创建一个变量。
For this function, I realized I don't even need the variable, as I can evaluate it straight in the if clause. 对于这个函数,我意识到我甚至不需要变量,因为我可以在if子句中直接评估它。
DELIMITER $$
DROP FUNCTION IF EXISTS fn_freq$$
CREATE FUNCTION fn_freq(days VarChar(7)) RETURNS INT
BEGIN
DECLARE x INT;
DECLARE fn_freq INT;
SET x =1, fn_freq = 0;
WHILE x < 8 DO
IF MID(days, x, 1) <> '_' THEN
SET fn_freq = fn_freq + 1;
END IF;
SET x = x + 1;
END WHILE;
RETURN fn_freq;
END$$
DELIMITER ;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.