mysql怎么动态创建一个表,mysql动态创建表

I am creating a database on mysql. First creating the principal tables which on average has 30 columns per table.

And the standard of the log table is the pk of the referenced table plus each column * 2.

Like this:

Referenced Table:

Field | Type | Null | Key | Default | Extra

--------+-------------+----------+---------+-------------+----------------

TableID | int(11) | No | PRI | Null | auto_increment

Col1 | varchar(50) | No | | Null |

Log Table:

Field | Type | Null | Key | Default | Extra

------------+-------------+----------+---------+-------------+----------------

LogTableID | int(11) | No | PRI | Null | auto_increment

TableID | int(11) | No | MUL | Null |

NewCol1 | varchar(50) | No | | Null |

UpdatedCol1 | varchar(50) | No | | Null |

Now what I want is to create a procedure on which I pass the table name as a parameter and generates the creation of the table log query and executes it.

What is the best way to do this?

解决方案

To make a string represent a table (or database) name you will need to concat your query string with the variable and prepare/execute a statement right in the stored procedure. Here's a basic example.

-- DROP PROCEDURE IF EXISTS createLogTable;

DELIMITER //

CREATE PROCEDURE createLogTable(tblName VARCHAR(255))

BEGIN

SET @tableName = tblName;

SET @q = CONCAT('

CREATE TABLE IF NOT EXISTS `' , @tableName, '` (

`id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,

`something` VARCHAR(10) NOT NULL,

`somedate` DATETIME NOT NULL,

PRIMARY KEY (`id`)

) ENGINE=MyISAM DEFAULT CHARSET=utf8

');

PREPARE stmt FROM @q;

EXECUTE stmt;

DEALLOCATE PREPARE stmt;

-- and you're done. Table is created.

-- process it here if you like (INSERT etc)

END //

Then… CALL createLogTable('exampleTable');

So the basic idea is

concat the procedure parameter(s) with your query as necessary

prepare/execute a statement from this query string

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值