Stored Procedures that creates a table - mysql

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.

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.

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

You can create a table in a stored procedure without a problem. Example:
delimiter |
create procedure createtab ()
begin
create table a(id int);
insert into a select 1;
select * from a;
drop table a;
end
|
delimiter ;

Something like this should work.
delimiter |
CREATE PROCEDURE SP_CREATE_TABLE( )
BEGIN
CREATE TABLE employees (emp_id int, emp_name varchar(100));
END;
|

Related

When I create a variable in create procedure on mySQL I get an error

//This is the code
create procedure st_insertRole(
#name varchar(30) //I get the error here
as
insert into roles values(#name)
);
here is the screenshot
My SQL does not allow session variables to be used for procedure parameters. You also have parentheses misplaced. The code in MySQL would look more like:
delimiter $$
create procedure st_insertRole (
in_name varchar(30)
)
begin
insert into roles (name)
values (in_name);
end; $$
The syntax is wrong
create procedure st_insertRole(
name_ varchar(30) )
insert into roles values(name_)
;

How to prevent “Table X was locked with a READ lock and can't be updated”?

I am using a MySQL table with date ranges. These date ranges may overlap, e. g. a date range from 2019-01-01 to 2019-01-10 and a second date range from 2019-01-05 to 2019-01-15. I need the combined date range for a time calculation, in the example, it would be 2019-01-01 to 2019-01-15. I wrote a procedure that creates a temporary table with the combined results.
Some functions use this temporary table for some time calculations. These functions call the procedure to create a temporary table, if not exists. But if the temporary table already exists, I get the error “Table was locked with a READ lock and can't be updated”. If I drop the temporary table before calling the create procedure, I do not get an error. But then every time the temporary table must be created again and the query takes almost a second to complete.
How can I prevent the error without dropping the temporary table every time?
Example:
drop database if exists TempTestDB;
create database TempTestDB;
USE `TempTestDB`;
create table TestTable(
test int auto_increment not null primary key,
name varchar(45))
;
-- real table has time data
INSERT INTO TestTable (`name`) VALUES ('test1');
DROP procedure IF EXISTS `createTempTestTable`;
DELIMITER $$
USE `TempTestDB`$$
CREATE DEFINER=`riedel`#`%` PROCEDURE `createTempTestTable`()
BEGIN
-- the temp table contains merged rows of the base table
CREATE TEMPORARY TABLE IF NOT EXISTS TempTestTable select * from TestTable;
INSERT INTO TempTestTable (`name`) VALUES ('test2');
END$$
DELIMITER ;
USE `TempTestDB`;
DELIMITER $$
USE `TempTestDB`$$
CREATE FUNCTION `getTimeForUser`(user int) RETURNS INT
BEGIN
-- real function does some time calculation
declare result int;
call TempTestDB.createTempTestTable;
select count(*) from TempTestTable into result;
RETURN result;
END$$
DELIMITER ;
select TempTestDB.getTimeForUser(1) union select TempTestDB.getTimeForUser(2);drop database if exists TempTestDB;
create database TempTestDB;
USE `TempTestDB`;
create table TestTable(
test int auto_increment not null primary key,
name varchar(45))
;
-- real table has time data
INSERT INTO TestTable (`name`) VALUES ('test1');
DROP procedure IF EXISTS `createTempTestTable`;
DELIMITER $$
USE `TempTestDB`$$
CREATE DEFINER=`riedel`#`%` PROCEDURE `createTempTestTable`()
BEGIN
-- the temp table contains merged rows of the base table
CREATE TEMPORARY TABLE IF NOT EXISTS TempTestTable select * from TestTable;
INSERT INTO TempTestTable (`name`) VALUES ('test2');
END$$
DELIMITER ;
USE `TempTestDB`;
DELIMITER $$
USE `TempTestDB`$$
CREATE FUNCTION `getTimeForUser`(user int) RETURNS INT
BEGIN
-- real function does some time calculation
declare result int;
call TempTestDB.createTempTestTable;
select count(*) from TempTestTable into result;
RETURN result;
END$$
DELIMITER ;
select TempTestDB.getTimeForUser(1) union select TempTestDB.getTimeForUser(2);

MySQL stored procedure for table insert error

I have below basic table:
create table hobbies (
id int primary key auto_increment,
name varchar(32) unique);
And I am trying to create a stored procedure to insert a new row in this table, like below:
delimiter //
create procedure add_hobby(hobby varchar(32))
begin
insert into hobbies(name) values(hobby);
end
delimiter //
call add_hobby('randomHobby');
When I call the procedure like above I am getting message "An unexpected error occured". I am running the queries on db-fiddle.com, MySQL ver 8.0. Could anyone offer some guidance if I've done something wrong or missed something? I can mention that procedure with select operation and no parameters works. Many thanks in advance.
You need to set your delimiter to begin with and then reset it at the end
for your parameters you need to set weather they are IN or out then the name and the type
delimiter //
create procedure add_hobby(IN hobby varchar(32))
begin
insert into hobbies(name) values(hobby);
end//
delimiter ;

Creating a MySQL Stored Procedure To Add a File To End of Existing Table

I am trying to create a stored procedure that will allow me to input a file, year, and string, and add it to the end of an existing table in MySQL. However, when I attempt to call the program it does not recognize the input file as a variable in the FROM clause. Does anyone have any tips for correcting this issue? I'm new to creating SQL programs but have looked into dynamic SQL, and was wondering if that might be an alternative? Thanks in advance for your help, and I'm happy to post any additional information.
Source File columns are ACS_Code and Descriptive_Title,
Output table columns are Year, Data_Profile, ACS_Code, and Descriptive_Title.
DELIMITER //
DROP PROCEDURE IF EXISTS `padata`.`Load_ACS_Data_Profile_Code_Def`//
CREATE PROCEDURE `padata`.Load_ACS_Data_Profile_Code_Def(IN file VARCHAR(255), IN Data_Profile Varchar(50), IN Year INT) # Input("Social","Economic","Housing",or "Demographic_Housing") for Dataprofile
BEGIN
INSERT INTO padata.ACS_5yr_Selected_Code_Definitions(
Year,
Data_Profile,
ACS_Code,
Descriptive_Title)
SELECT
Year AS Year,
Data_Profile AS Data_Profile,
a.ACS_Code AS ACS_Code,
a.Descriptive_Title AS Descriptive_Title
FROM
`padata`.file a ; #Where file is a parameter that is passed
END //
DELIMITER ;
And here is the call command and error information:
CALL `padata`.Load_ACS_Data_Profile_Code_Def ('2010_5yr_Selected_Social_Metadata', 'Social', 2010)
Error Code: 1146. Table 'padata.file' doesn't exist
what is file, it seems to me you are referring to an file on your operating system. Don't say it is an input file. It is a varchar (string).
It certainly isn't a table in db called padata.
The stored proc IN means you are passing in a parameter such as a string, int sort of thing. It does not open up a stream reading from a file.
Edit:
drop schema so_gibberish;
create schema so_gibberish;
use so_gibberish;
create table thisTable
(
id int not null auto_increment primary key,
favF int not null,
fullName varchar(100) not null
);
insert thisTable (fullName,favF) values ('Jimmy Johnson',2),('Kelly Kipper',3);
create table thatTable
(
id int not null auto_increment primary key,
favF int not null,
fullName varchar(100) not null
);
insert thatTable (fullName,favF) values ('Jennie Jugggs',1),('Zach Zipper',4);
create table favFruit
(
id int not null auto_increment primary key,
fruit varchar(100) not null
);
insert favFruit(fruit) values ('banana'),('kiwi'),('raspberries'),('honey dew melon');
DELIMITER $$
drop procedure if exists so_gibberish.doSomething$$
CREATE PROCEDURE so_gibberish.doSomething
(tblName varchar(100))
BEGIN
SET #statement=concat('select p.fullName,f.fruit from ',tblName,' p join favFruit f on f.id=p.favF');
PREPARE stmt FROM #statement;
execute stmt;
deallocate prepare stmt;
END;
$$
DELIMITER ;
call doSomething('thisTable');
Jimmy Johnson kiwi
Kelly Kipper raspberries
call doSomething('thatTable');
Jennie Jugggs banana
Zach Zipper honey dew melon

Create new table procedure

I'm trying to create a procedure which adds / removes a table to the database. I'm working in SQL Server. The query works (it succeeds) but the table isn't added to the database.
I did refreshed...
ALTER procedure [dbo].[upgrade_1]
as
begin
create table awards (
ID int NOT NULL IDENTITY,
name nvarchar(256) DEFAULT 'award',
description nvarchar(256)
PRIMARY KEY (ID)
)
/*update goto_vs
set current_version = 1*/
end
The script you have in the question will only modify the PROCEDURE. The procedure needs to be executed for it to perform the required task e.g. create the table
Execute the procedure with this statement
EXEC upgrade_1
That should create the table