我正在尝试在MySQL存储过程中连接变量和字符串。

huangapple go评论55阅读模式
英文:

I am trying to concat variable and string in stored procedure in mysql

问题

我正在尝试在MySQL存储过程中将变量和字符串连接起来以用作SELECT语句中的表名。

CREATE DEFINER=`root`@`localhost` PROCEDURE `test`()
BEGIN
DECLARE demo1 VARCHAR(100);
DECLARE demo2 VARCHAR(100);
DECLARE concatenated VARCHAR(100);
DECLARE concatenated2 VARCHAR(100);
SET demo1 = ('tour_');
SET demo2 = ('companytb');
SET concatenated = CONCAT('tour_', 'companytb');
SET concatenated2 = CONCAT_WS(demo1, demo2);
SELECT DISTINCT company_name FROM concatenated;
END

但我尝试了这个,但是我收到了以下错误信息:

Error Code: 1146. Table 'codimbii_live.concatenated' doesn't exist
英文:

I am trying to concatenate variable and string in mysql stored procedure for table name in select

CREATE DEFINER=`root`@`localhost` PROCEDURE `test`()
BEGIN
DECLARE demo1 VARCHAR(100);
DECLARE demo2 VARCHAR(100);
DECLARE concatenated VARCHAR(100);
DECLARE concatenated2 VARCHAR(100);
SET demo1 = ('tour_');
SET demo2 = ('companytb');
SET concatenated = CONCAT('tour_', 'companytb');
SET concatenated2 = CONCAT_WS(demo1, demo2);
SELECT DISTINCT company_name FROM concatenated;
END

I tried this, but I am getting this error:

>01911:41:29 call test()
>
> Error Code: 1146. Table 'codimbii_live.concatenated' doesn't exist

答案1

得分: 0

如@akina在评论中提到的,您需要使用一些预处理语句,这里是一个示例:

CREATE DEFINER=`root`@`localhost` PROCEDURE `test`()
BEGIN
  DECLARE demo1 VARCHAR(100);
  DECLARE demo2 VARCHAR(100);
  DECLARE concatenated VARCHAR(100);
  DECLARE concatenated2 VARCHAR(100);
  SET demo1 = ('tour_');
  SET demo2 = ('companytb');
  SET @sql = CONCAT('SELECT DISTINCT company_name FROM ', demo1, demo2);
  PREPARE stmt FROM @sql;EXECUTE stmt;DEALLOCATE PREPARE stmt;
END
英文:

As mentioned by @akina in comments you will need to use some prepared statements, here is an exemple :

CREATE DEFINER=`root`@`localhost` PROCEDURE `test`()
BEGIN
  DECLARE demo1 VARCHAR(100);
  DECLARE demo2 VARCHAR(100);
  DECLARE concatenated VARCHAR(100);
  DECLARE concatenated2 VARCHAR(100);
  SET demo1 = ('tour_');
  SET demo2 = ('companytb');
  SET @sql = CONCAT('SELECT DISTINCT company_name FROM ', demo1, demo2);
  PREPARE stmt FROM @sql;EXECUTE stmt;DEALLOCATE PREPARE stmt;
END

huangapple
  • 本文由 发表于 2023年6月26日 14:17:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76553968.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定