Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stored Procedures that creates a table

Can I create tables using Stored Procedures?

I am using MySQL. I had searched the web for instructions on how to create a table using stored procedure, but I didn't find any results, I just found that you can create temporary tables. Is there any problem if I create tables using stored procedures?

Actually I want to check whether a table exists or not, then I have to create it.

like image 596
sasi Avatar asked Jun 19 '12 12:06

sasi


Video Answer


2 Answers

You can create tables using procedures in mysql.

delimiter |
CREATE PROCEDURE SP_CREATE_TABLE_TEST ()
   BEGIN
      CREATE TABLE TEST 
      (
        TestID int(11) default NULL,
        TestName varchar(100) default NULL
      ) 
      ENGINE=InnoDB DEFAULT CHARSET=utf8;
   END;

|

Reference link.

like image 104
Nirmal Avatar answered Nov 22 '22 05:11

Nirmal



EDIT: Thanks Peter! So the solution to this particular problem:

DELIMITER //
CREATE PROCEDURE createTable(IN tableName VARCHAR(40))
BEGIN
SET @table := tableName;
SET @sql_text:=CONCAT('CREATE TABLE ',@table,'(id INT NOT NULL AUTO_INCREMENT, FILENAME VARCHAR(40) NOT NULL, DATA BLOB NOT NULL, PRIMARY KEY (ID))');

PREPARE stmt from @sql_text;
EXECUTE stmt;
END //
DELIMITER ;

In addition to the manual I also found a very helpful tut by Roland Bouman at:

http://rpbouman.blogspot.com/2005/11/mysql-5-prepared-statement-syntax-and.htmlenter code here

El autor de la respuesta: Conrad Ljungström

link de la respuesta original: https://forums.mysql.com/read.php?98,495352

like image 27
alex coillo chambilla Avatar answered Nov 22 '22 04:11

alex coillo chambilla