MySQL IF THEN condition to Drop a table - mysql

I am trying to use stored procedure and check on a particular table and use IF THEN condition to drop the table. Is it possible to issue the DROP statement in the conditional block?
delimiter $$
CREATE PROCEDURE FC_SQLF()
BEGIN
DECLARE SQLFOUND int;
SET #SQLFOUND = (select count(table_name) from information_schema.tables where table_schema = 'testdb' and table_name = 'temp_table');
IF #SQLFOUND = 1 THEN DROP TABLE testdb.abcd;
END IF;
END $$

Related

Mysql calling procedure failed when dynamically alter table in it

I want to alter my tables dynamically based on whether the table has specific column.
My database name is summer_cms, and there are over 50 tables in it.
What I want are below:
If a table has a column named add_time, then I would like to add a column add_user_id in it.
Similarly, I would like to add update_user_id in the table if update_time is found.
I know I should get it down in the process of creating the database schemas, but my database has been built and I have to alter it by need.
So I create a procedure to do it:
CREATE PROCEDURE ALTER_SUMMER_TABLE()
BEGIN
DECLARE tableName VARCHAR(64);
DECLARE exitence VARCHAR(64);
DECLARE ntable INT; # number of tables
DECLARE i INT; # index
SET i = 0;
# get the count of table
SELECT COUNT(DISTINCT(TABLE_NAME)) INTO ntable FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = 'summer_cms';
WHILE i < ntable DO
# select the specific table name into the variable of `tableName`.
SELECT TABLE_NAME INTO tableName
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = 'summer_cms'
AND COLUMN_NAME = 'add_time'
LIMIT 1 OFFSET i;
# alter table, but I get error in this clause.
ALTER TABLE tableName ADD COLUMN `add_user_id` INT NOT NULL DEFAULT 0 COMMENT 'add user id';
# check if the table has `update_time`
SELECT TABLE_NAME INTO exitence
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = 'summer_cms'
AND TABLE_NAME = tableName
AND COLUMN_NAME = 'update_time';
# add `update_user_id` if `update_time` be found.
IF exitence THEN
ALTER TABLE tableName ADD COLUMN `update_user_id` INT NOT NULL DEFAULT 0 COMMENT 'update user id';
END IF;
SET i = i + 1;
END WHILE;
END
But I got an error when I call this procedure.
Procedure execution failed
1146 - Table 'summer_cms.tableName' doesn't exist
Dose anyone could tell me what I was missing or wrong? Any help will be appreciated.
There a a few alterations you can make to your procedure to make it more streamlined as well as getting round a few problems.
First using a cursor to select the table names rather than using the two selects your using. Secondly to use a prepared statement to allow you to dynamically set the table name...
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `ALTER_SUMMER_TABLE`()
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE tableName VARCHAR(64);
declare cur cursor for SELECT TABLE_NAME
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = 'summer_cms'
AND COLUMN_NAME = 'add_time';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
open cur;
start_loop: loop
fetch cur into tableName;
if (done = 1 )THEN
LEAVE start_loop;
END IF;
SET #sql = CONCAT('ALTER TABLE ', tableName,' ADD COLUMN `add_user_id` INT NOT NULL DEFAULT 0 ');
PREPARE stmt FROM #sql;
EXECUTE stmt;
end loop;
close cur;
END$$
DELIMITER ;
You could do a few tweaks - only fetch table names where the column doesn't already exist for example.
Here's an example of dynamic sql
drop procedure if exists alter_table;
delimiter //
CREATE DEFINER=`root`#`localhost` procedure alter_table()
begin
declare tablename varchar(20);
set tablename = 'u';
set #sqlstmt = concat('ALTER TABLE ', tableName, ' ADD COLUMN ', char(96), 'add_user_id', char(96), ' INT NOT NULL DEFAULT 0 COMMENT', char(39), 'add user id', char(39),';');
prepare stmt from #sqlstmt;
execute stmt;
deallocate prepare stmt;
end //
delimiter ;
Note I have used ascii backticks and single quotes.

Create temporary table in procedure, MySql

I need create a simple procedure, but after create a temporary table, mysql wants put 'end' after semicolon.
CREATE procedure zad2()
begin
drop temporary table if exists temp;
create temporary table temp as (select table_name, column_name
from information_schema.columns where table_schema = 'lista3' and table_name not like 'lista');
declare i int default 0;
end$$
SQL Stored procedure have a block where you will put all code/logic .. and that block is BEGIN and END , if you have an opening block which is BEGIN , you need to close it with END, that's why MySql wants you to put END after semi colon.
Below link can help with the syntax:
CREATE PROCEDURE and CREATE FUNCTION Syntax
I think that what is missing is to declare the DELIMITER $$ at the start of the statement:
DELIMITER $$ /*To tell MySQL that your delimiter is now '$$' */
CREATE procedure zad2()
begin
drop temporary table if exists temp;
create temporary table temp as (select table_name, column_name
from information_schema.columns where table_schema = 'lista3' and table_name not like 'lista');
declare i int default 0;
end$$
DELIMITER ; /*To tell your MySQL that you delimiter is back ';' */

Error 1064 (42000) on create procedure MySQL

I'm having this specific error when trying to create a stored procedure on MySQL database:
CREATE PROCEDURE GET_COLUMNS(TABLENAME VARCHAR(50))
BEGIN
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'SolarTV' AND TABLE_NAME=TABLENAME;
END
All you should need to do here is temporarily change the delimiter while defining the procedure, then set it back to ; after the procedure has been created. Otherwise it'll get confused when it sees the first ; from within the procedure definition. Example:
DELIMITER //
CREATE PROCEDURE GET_COLUMNS(TABLENAME VARCHAR(50))
BEGIN
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'SolarTV' AND TABLE_NAME=TABLENAME;
END//
DELIMITER ;

Loop through array in mysql Stored procs

I need to dynamically alter set of tables
Currently i can alter only one using below SP.
DROP PROCEDURE IF EXISTS add_version_to_actor;
DELIMITER $$
CREATE DEFINER=CURRENT_USER PROCEDURE add_version_to_actor (IN table_name VARCHAR(40) )
BEGIN
DECLARE colName TEXT;
SELECT column_name INTO colName
FROM information_schema.columns
WHERE table_schema = 'database_name'
AND table_name = table_name
AND column_name = 'column';
IF colName is null THEN
Alter Table database_name.table_name ADD `sequence` INT( 10 ) NOT NULL;
END IF;
END$$
DELIMITER ;
CALL add_version_to_actor('table1');
DROP PROCEDURE add_version_to_actor;
Currently 'table1' is a single parameter. I need to pass multiple table names as string like this CALL add_version_to_actor('table1','table2');and loop through all of them.How can this be achieved.
Thanks in advance.

MySQL Procedure: If column don't exists create it

I try to make procedure that create non-exists column in my MySQL table like here:
MySQL add column if not exist
My procedure:
DELIMITER $$
CREATE PROCEDURE Alter_Table(IN _table_name TEXT,IN _column_name TEXT,IN _column_type TEXT)
BEGIN
DECLARE _count INT;
SET _count = ( SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = _table_name AND
COLUMN_NAME = _column_name);
IF _count = 0 THEN
ALTER TABLE _table_name ADD COLUMN _column_name _column_type;
END IF;
END $$
DELIMITER ;
But I have an error:
#1064 - Something is wrong in your syntax obok '_column_type; END IF; END' w linii 9
Anyone know why?
Ok... I make it in PHP...
function alter_table($table_name, $column_name, $column_type) {
$result = mysql_query("SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = `$table_name` AND COLUMN_NAME = `$column_name`");
if(!$result) {
mysql_query("ALTER TABLE `$table_name`
ADD COLUMN `$column_name` $column_type");
}
}