Procedure to create database and tables

Asked

Viewed 441 times

1

I need to create a data bank for each client that makes a certain registration, for this I created a procedure to do such a thing.

But I came across a small identification problem. When I run the procedure it creates the database with the name I passed by parameter, but when creating the tables, it creates the tables in my matrix database where the procedure was created, I tried to use the USE nome_do_bando to reference but did not work. follows the example code:

DELIMITER $$

USE `loja_virtual_dev`$$

DROP PROCEDURE IF EXISTS `cria_banco_cliente`$$

CREATE DEFINER=`loja_virtual_dev`@`%` PROCEDURE `cria_banco_cliente`(IN var_banco VARCHAR(40))
main:BEGIN
    IF(var_banco <> '') THEN
        SELECT var_banco AS msg;
        SET @teste = CONCAT("CREATE DATABASE ",var_banco," DEFAULT CHARACTER SET latin1");
        PREPARE stmt1 FROM @teste;
        EXECUTE stmt1;
        DEALLOCATE PREPARE stmt1;

        -- USE `var_banco`$$

        SET @sql1 := CONCAT("CREATE TABLE IF NOT EXISTS teste_loja (
          id int NOT NULL,
          data date NOT NULL,
          cliente int DEFAULT FALSE,
          id_const int DEFAULT FALSE
        ) ENGINE = innoDB");

          PREPARE stmt2 FROM @sql1;
          EXECUTE stmt2;
          DEALLOCATE PREPARE stmt1;


        LEAVE main;
    END IF;



END$$

DELIMITER ;
  • You need to run the database that creates the new database, connect to it, create the database that creates the tables in the new database and run this database from there.

  • What is your front-end?

  • 1

    try to use your USE bank$$ within the SET @sql1 := CONCAT(" USE bank$$ CREATE TABLE IF NOT EXISTS teste_loja ( ...........

  • I’m using php with the codeigniter framework! , Marconcilio I tried to put USE inside the SET but it didn’t work.

1 answer

1

Solved. The simplest solution I could find was this:

i created the table by passing_database.table name_table.

SET @sql1 := CONCAT("CREATE TABLE IF NOT EXISTS ",var_banco,".teste_loja (
          id int NOT NULL,
          data date NOT NULL,
          cliente int DEFAULT FALSE,
          id_const int DEFAULT FALSE
        ) ENGINE = innoDB");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.