MySQL Select into variable

会有一股神秘感。 提交于 2019-12-06 10:37:55
Frank Thomas

Try changing 'SELECT 1,2 into v_1, v_2' to

'SELECT @v_1:=1, @v_2:=2'

or at least make sure you use @ whenever referencing your vars. see this thread for more info: SELECT INTO Variable in MySQL DECLARE causes syntax error?

If you do not need the dynamic SQL inside your procedure, you can simpler syntax:

DECLARE v_1 INT;   DECLARE v_2 INT;   DECLARE v_3 INT;

SELECT 1,2 into v_1, v_2;
SET v_3 = v_1 + v_2;
SELECT v_3;

Using normal variables declared inside stored procedure are safer than the user-defined variables (@-variables) as a call to another stored procedure may change your user-defined variable value.

You need to modify little code to work properly see my modification

DECLARE v_1 INT;
DECLARE v_2 INT;
DECLARE v_3 INT;

SET @sql=CONCAT('SELECT 1,2 into @v1, @v2');
PREPARE s1 FROM @sql;
EXECUTE s1;

SELECT @v1, @v2 INTO v_1, v_2;
SET v_3 = v_1 + v_2;
SELECT v_3;

DEALLOCATE PREPARE s1;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!