gpt4 book ai didi

mysql - 使用动态 MySQL 创建新表

转载 作者:行者123 更新时间:2023-11-30 23:02:23 25 4
gpt4 key购买 nike

我想更改此查询:

CREATE TABLE diablo.diablo_sales2 LIKE diablo.diablo_sales;

像这样动态的:

set @old = 'diablo_sales';
set @new = 'diablo_sales2 ';
set @schema = 'diablo';

set @query = 'create table @schema.@new like @schema.@old';

这在 MySQL 中甚至可能吗?如何执行@query?

编辑:下面是我试图动态化的整个查询

 -- create same table structure - blank table
CREATE TABLE diablo.diablo_sales2 LIKE diablo.diablo_sales;

-- add the new column(s)
ALTER TABLE diablo.diablo_sales2
add column new_column decimal(10);


-- insert the old data into new table - new column will remain blank
INSERT INTO diablo.diablo_sales2
(
column1,
column2

)
SELECT * FROM diablo.diablo_sales;

-- rename the new table to its original name. Drop the old table.
RENAME table diablo_sales TO `old`, diablo_sales2 TO diablo_sales;
DROP TABLE old;

最佳答案

您可以使用 SQL Syntax for Prepared Statements :

SET @sql := CONCAT('
CREATE TABLE `',REPLACE(@schema,'`','``'),'`.`',REPLACE(@new,'`','``'),'`
LIKE `',REPLACE(@schema,'`','``'),'`.`',REPLACE(@old,'`','``'),'`
');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

我冒昧地引用了标识符并调用了 REPLACE()转义其中包含的任何引号,以防止 SQL 注入(inject)。

关于mysql - 使用动态 MySQL 创建新表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23400359/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com