【问题标题】:Is it possible to dynamically create the name of a table in a stored procedure with MySQL?是否可以使用 MySQL 在存储过程中动态创建表的名称?
【发布时间】:2014-02-25 17:14:46
【问题描述】:

看看这段代码。它应该向您展示我正在尝试做的事情:

SELECT type from barcodes where barcode = barcodeApp INTO @barcodeType;
IF (@barcodeType = 'videogame') THEN 
    SET @barcodeType = 'game';
END IF;

DELETE FROM @barcodeType + itemdetails_custom
WHERE barcode = barcodeApp
AND username = usernameApp;

如您所见,在DELETE FROM 部分,我想动态地将先前查询结果中的表名放在一起。这可能吗?

另外,如果您发现上述查询有问题,请告诉我。我显然不是 MySQL 专家。

【问题讨论】:

  • barcodeAppusernameApp 是什么?变量或列名?
  • 是的,变量从用户发送到存储过程中

标签: mysql sql select stored-procedures sql-delete


【解决方案1】:

您需要使用Prepared Statement 来执行动态准备的查询。

试试下面的代码:

set @del_query = concat( 'DELETE FROM ', @finalType )
set @del_query = concat( '\'', itemdetails_custom, '\'' );
set @del_query = concat( @del_query, ' WHERE barcode = \'', barcodeApp, '\'' );
set @del_query = concat( @del_query, ' AND username = \'', usernameApp, '\'' );

prepare stmt from @del_query;
execute stmt;
drop prepare stmt; -- deallocate prepare stmt; 

注意:我假设barcodeAppusernameApp 是变量。否则在上面的查询中删除它们周围的单引号。

【讨论】:

  • 有效!不过,您忘记了 itemdetails_custom 周围的单引号。 :)
猜你喜欢
  • 2017-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-24
  • 1970-01-01
  • 1970-01-01
  • 2019-06-02
相关资源
最近更新 更多