MySQL add column if not exist - mysql

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'email_subscription' AND COLUMN_NAME = 'subscribe_all')
THEN
ALTER TABLE email_subscription
ADD COLUMN subscribe_all TINYINT(1) DEFAULT 1,
ADD COLUMN subscribe_category varchar(512) DEFAULT NULL;
I had a look at huge amount of examples. but this query doesn't work, I got error of:
ERROR 1064 (42000): You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right
syntax to use near 'IF NOT EXISTS (SELECT * FROM
INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME =' at line 1

If your host doesn't give you permission to create or run procedures, I think I found another way to do this using PREPARE/EXECUTE and querying the schema:
SET #s = (SELECT IF(
(SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'table_name'
AND table_schema = DATABASE()
AND column_name = 'col_name'
) > 0,
"SELECT 1",
"ALTER TABLE table_name ADD col_name VARCHAR(100)"
));
PREPARE stmt FROM #s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

you can create a procedure for the query,
DELIMITER $$
CREATE PROCEDURE Alter_Table()
BEGIN
DECLARE _count INT;
SET _count = ( SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'email_subscription' AND
COLUMN_NAME = 'subscribe_all');
IF _count = 0 THEN
ALTER TABLE email_subscription
ADD COLUMN subscribe_all TINYINT(1) DEFAULT 1,
ADD COLUMN subscribe_category varchar(512) DEFAULT NULL;
END IF;
END $$
DELIMITER ;

There is no equivalent syntax to achieve this in a single MySQL statement.
To get something simlilar, you can either
1) attempt to add the column with an ALTER TABLE, and let MySQL raise an error if a column of that name already exists in the table, or
2) query the information_schema.columns view to check if a column of that name exists in the table.
Note that you really do need to check for the table_schema, as well as the table_name:
SELECT column_name
FROM information_schema.columns
WHERE table_schema = 'foo'
AND table_name = 'email_subscription'
AND column_name = 'subscribe_all'
and based on that, decide whether to run the ALTER TABLE

You are using MS SQL Server syntax in MySQL.

Also add condition for database name to check column existance.
Try this:
DELIMITER $$
CREATE PROCEDURE sp_AlterTable()
BEGIN
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'dbName' AND
TABLE_NAME = 'email_subscription' AND
COLUMN_NAME = 'subscribe_all') THEN
ALTER TABLE email_subscription
ADD COLUMN subscribe_all TINYINT(1) DEFAULT 1,
ADD COLUMN subscribe_category VARCHAR(512) DEFAULT NULL;
END IF;
END $$
DELIMITER ;

SET #s = (SELECT IF(
(SELECT COUNT(column_name)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'oc_bitcoin_wallets_receive'
AND table_schema = 'k_opencart2'
AND column_name = 'test3'
) > 0,
"SELECT 1",
"ALTER TABLE `oc_bitcoin_wallets_receive` ADD COLUMN `test3` INT NOT NULL AFTER `test2`;"
));
PREPARE stmt FROM #s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Values for edit:
oc_bitcoin_wallets_receive - table name,
k_opencart2 - database name,
test3 - name of new column,
oc_bitcoin_wallets_receive - second location table
test3 - second location column,
test2 - name of column before new column.

Related

ERROR 1064 (42000) / Wrong SQL Syntax but i dont know why? [duplicate]

I have this code:
ALTER TABLE `settings`
ADD COLUMN `multi_user` TINYINT(1) NOT NULL DEFAULT 1
And I want to alter this table only if this column doesn't exist.
I'm trying a lot of different ways, but nothing works:
ALTER TABLE `settings`
ADD COLUMN IF NOT EXISTS `multi_user` TINYINT(1) NOT NULL DEFAULT 1
With procedure:
DELIMITER $$
CREATE PROCEDURE Alter_Table()
BEGIN
DECLARE _count INT;
SET _count = ( SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'settings' AND
COLUMN_NAME = 'multi_user');
IF _count = 0 THEN
ALTER TABLE `settings` ADD COLUMN `multi_user` TINYINT(1) NOT NULL DEFAULT 1
END IF;
END $$
DELIMITER ;
I got error in END IF, then in END and then in 1
How can I make this as simple as possible?
Use the following in a stored procedure:
IF NOT EXISTS( SELECT NULL
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'tablename'
AND table_schema = 'db_name'
AND column_name = 'columnname') THEN
ALTER TABLE `TableName` ADD `ColumnName` int(1) NOT NULL default '0';
END IF;
Use PREPARE/EXECUTE and querying the schema.
The host doesn't need to have permission to create or run procedures :
SET #dbname = DATABASE();
SET #tablename = "tableName";
SET #columnname = "colName";
SET #preparedStatement = (SELECT IF(
(
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
WHERE
(table_name = #tablename)
AND (table_schema = #dbname)
AND (column_name = #columnname)
) > 0,
"SELECT 1",
CONCAT("ALTER TABLE ", #tablename, " ADD ", #columnname, " INT(11);")
));
PREPARE alterIfNotExists FROM #preparedStatement;
EXECUTE alterIfNotExists;
DEALLOCATE PREPARE alterIfNotExists;
Here is a solution that does not involve querying INFORMATION_SCHEMA, it simply ignores the error if the column does exist.
DROP PROCEDURE IF EXISTS `?`;
DELIMITER //
CREATE PROCEDURE `?`()
BEGIN
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION BEGIN END;
ALTER TABLE `table_name` ADD COLUMN `column_name` INTEGER;
END //
DELIMITER ;
CALL `?`();
DROP PROCEDURE `?`;
P.S. Feel free to give it other name rather than ?
Add field if not exist:
CALL addFieldIfNotExists ('settings', 'multi_user', 'TINYINT(1) NOT NULL DEFAULT 1');
addFieldIfNotExists code:
DELIMITER $$
DROP PROCEDURE IF EXISTS addFieldIfNotExists
$$
DROP FUNCTION IF EXISTS isFieldExisting
$$
CREATE FUNCTION isFieldExisting (table_name_IN VARCHAR(100), field_name_IN VARCHAR(100))
RETURNS INT
RETURN (
SELECT COUNT(COLUMN_NAME)
FROM INFORMATION_SCHEMA.columns
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = table_name_IN
AND COLUMN_NAME = field_name_IN
)
$$
CREATE PROCEDURE addFieldIfNotExists (
IN table_name_IN VARCHAR(100)
, IN field_name_IN VARCHAR(100)
, IN field_definition_IN VARCHAR(100)
)
BEGIN
SET #isFieldThere = isFieldExisting(table_name_IN, field_name_IN);
IF (#isFieldThere = 0) THEN
SET #ddl = CONCAT('ALTER TABLE ', table_name_IN);
SET #ddl = CONCAT(#ddl, ' ', 'ADD COLUMN') ;
SET #ddl = CONCAT(#ddl, ' ', field_name_IN);
SET #ddl = CONCAT(#ddl, ' ', field_definition_IN);
PREPARE stmt FROM #ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;
END;
$$
this is not original, but it IS copy-and-paste
source: javajon.blogspot.com/2012/10/
I used this approach (Without using stored procedure):
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'tbl_name' AND COLUMN_NAME = 'column_name'
If it didnt return any rows then the column doesn't exists then alter the table:
ALTER TABLE tbl_name
ADD COLUMN column_name TINYINT(1) NOT NULL DEFAULT 1
Hope this helps.
hope this will help you
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'tbl_name'
AND table_schema = 'db_name'
AND column_name = 'column_name'
or
delimiter '//'
CREATE PROCEDURE addcol() BEGIN
IF NOT EXISTS(
SELECT * FROM information_schema.COLUMNS
WHERE COLUMN_NAME='new_column' AND TABLE_NAME='tablename' AND TABLE_SCHEMA='the_schema'
)
THEN
ALTER TABLE `the_schema`.`the_table`
ADD COLUMN `new_column` TINYINT(1) NOT NULL DEFAULT 1;;
END IF;
END;
//
delimiter ';'
CALL addcol();
DROP PROCEDURE addcol;
$sql="SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Your_Table_Name' AND COLUMN_NAME = 'Your_New_Column_Name'";
$RESULT = mysqli_query($conn,$sql);
The abobe query return 0 if the column is not present in your table then you need to run alter query like below
if($RESULT){
$sqll="ALTER TABLE Your_table_Name ADD COLUMN Your_New_Column_Name varchar(20) NOT NULL DEFAULT 0";
}
SET #dbname = DATABASE();
SET #tablename = "table";
SET #columnname = "fieldname";
SET #preparedStatement = (SELECT IF(
(
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
WHERE
(table_name = #tablename)
AND (table_schema = #dbname)
AND (column_name = #columnname)
) > 0,
"SELECT 1",
CONCAT("ALTER TABLE ", #tablename, " ADD ", #columnname, " DECIMAL(18,4) NULL;")
));
PREPARE alterIfNotExists FROM #preparedStatement;
EXECUTE alterIfNotExists;
DEALLOCATE PREPARE alterIfNotExists;
This below worked for me:
SELECT count(*)
INTO #exist
FROM information_schema.columns
WHERE table_schema = 'mydatabase'
and COLUMN_NAME = 'mycolumn'
AND table_name = 'mytable' LIMIT 1;
set #query = IF(#exist <= 0, 'ALTER TABLE mydatabase.`mytable` ADD COLUMN `mycolumn` MEDIUMTEXT NULL',
'select \'Column Exists\' status');
prepare stmt from #query;
EXECUTE stmt;
Sometimes it may happen that there are multiple schema created in a database.
So to be specific schema we need to target, so this will help to do it.
SELECT count(*) into #colCnt FROM information_schema.columns WHERE table_name = 'mytable' AND column_name = 'mycolumn' and table_schema = DATABASE();
IF #colCnt = 0 THEN
ALTER TABLE `mytable` ADD COLUMN `mycolumn` VARCHAR(20) DEFAULT NULL;
END IF;
Using this as an example:
https://dbabulletin.com/index.php/2018/03/29/best-practices-using-flyway-for-database-migrations/
DELIMITER $$
DROP PROCEDURE IF EXISTS upgrade_database_4_to_5 $$
CREATE PROCEDURE upgrade_database_4_to_5()
BEGIN
IF NOT EXISTS( (SELECT * FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE()
AND COLUMN_NAME='multi_user' AND TABLE_NAME='settings') ) THEN
ALTER TABLE `settings` ADD COLUMN `multi_user` TINYINT(1) NOT NULL DEFAULT 1;
END IF;
END $$
CALL upgrade_database_4_to_5() $$
DELIMITER ;

What is the correct syntax of IF NOT EXISTS in MySQL 5.7.25? [duplicate]

I have this code:
ALTER TABLE `settings`
ADD COLUMN `multi_user` TINYINT(1) NOT NULL DEFAULT 1
And I want to alter this table only if this column doesn't exist.
I'm trying a lot of different ways, but nothing works:
ALTER TABLE `settings`
ADD COLUMN IF NOT EXISTS `multi_user` TINYINT(1) NOT NULL DEFAULT 1
With procedure:
DELIMITER $$
CREATE PROCEDURE Alter_Table()
BEGIN
DECLARE _count INT;
SET _count = ( SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'settings' AND
COLUMN_NAME = 'multi_user');
IF _count = 0 THEN
ALTER TABLE `settings` ADD COLUMN `multi_user` TINYINT(1) NOT NULL DEFAULT 1
END IF;
END $$
DELIMITER ;
I got error in END IF, then in END and then in 1
How can I make this as simple as possible?
Use the following in a stored procedure:
IF NOT EXISTS( SELECT NULL
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'tablename'
AND table_schema = 'db_name'
AND column_name = 'columnname') THEN
ALTER TABLE `TableName` ADD `ColumnName` int(1) NOT NULL default '0';
END IF;
Use PREPARE/EXECUTE and querying the schema.
The host doesn't need to have permission to create or run procedures :
SET #dbname = DATABASE();
SET #tablename = "tableName";
SET #columnname = "colName";
SET #preparedStatement = (SELECT IF(
(
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
WHERE
(table_name = #tablename)
AND (table_schema = #dbname)
AND (column_name = #columnname)
) > 0,
"SELECT 1",
CONCAT("ALTER TABLE ", #tablename, " ADD ", #columnname, " INT(11);")
));
PREPARE alterIfNotExists FROM #preparedStatement;
EXECUTE alterIfNotExists;
DEALLOCATE PREPARE alterIfNotExists;
Here is a solution that does not involve querying INFORMATION_SCHEMA, it simply ignores the error if the column does exist.
DROP PROCEDURE IF EXISTS `?`;
DELIMITER //
CREATE PROCEDURE `?`()
BEGIN
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION BEGIN END;
ALTER TABLE `table_name` ADD COLUMN `column_name` INTEGER;
END //
DELIMITER ;
CALL `?`();
DROP PROCEDURE `?`;
P.S. Feel free to give it other name rather than ?
Add field if not exist:
CALL addFieldIfNotExists ('settings', 'multi_user', 'TINYINT(1) NOT NULL DEFAULT 1');
addFieldIfNotExists code:
DELIMITER $$
DROP PROCEDURE IF EXISTS addFieldIfNotExists
$$
DROP FUNCTION IF EXISTS isFieldExisting
$$
CREATE FUNCTION isFieldExisting (table_name_IN VARCHAR(100), field_name_IN VARCHAR(100))
RETURNS INT
RETURN (
SELECT COUNT(COLUMN_NAME)
FROM INFORMATION_SCHEMA.columns
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = table_name_IN
AND COLUMN_NAME = field_name_IN
)
$$
CREATE PROCEDURE addFieldIfNotExists (
IN table_name_IN VARCHAR(100)
, IN field_name_IN VARCHAR(100)
, IN field_definition_IN VARCHAR(100)
)
BEGIN
SET #isFieldThere = isFieldExisting(table_name_IN, field_name_IN);
IF (#isFieldThere = 0) THEN
SET #ddl = CONCAT('ALTER TABLE ', table_name_IN);
SET #ddl = CONCAT(#ddl, ' ', 'ADD COLUMN') ;
SET #ddl = CONCAT(#ddl, ' ', field_name_IN);
SET #ddl = CONCAT(#ddl, ' ', field_definition_IN);
PREPARE stmt FROM #ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;
END;
$$
this is not original, but it IS copy-and-paste
source: javajon.blogspot.com/2012/10/
I used this approach (Without using stored procedure):
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'tbl_name' AND COLUMN_NAME = 'column_name'
If it didnt return any rows then the column doesn't exists then alter the table:
ALTER TABLE tbl_name
ADD COLUMN column_name TINYINT(1) NOT NULL DEFAULT 1
Hope this helps.
hope this will help you
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'tbl_name'
AND table_schema = 'db_name'
AND column_name = 'column_name'
or
delimiter '//'
CREATE PROCEDURE addcol() BEGIN
IF NOT EXISTS(
SELECT * FROM information_schema.COLUMNS
WHERE COLUMN_NAME='new_column' AND TABLE_NAME='tablename' AND TABLE_SCHEMA='the_schema'
)
THEN
ALTER TABLE `the_schema`.`the_table`
ADD COLUMN `new_column` TINYINT(1) NOT NULL DEFAULT 1;;
END IF;
END;
//
delimiter ';'
CALL addcol();
DROP PROCEDURE addcol;
$sql="SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Your_Table_Name' AND COLUMN_NAME = 'Your_New_Column_Name'";
$RESULT = mysqli_query($conn,$sql);
The abobe query return 0 if the column is not present in your table then you need to run alter query like below
if($RESULT){
$sqll="ALTER TABLE Your_table_Name ADD COLUMN Your_New_Column_Name varchar(20) NOT NULL DEFAULT 0";
}
SET #dbname = DATABASE();
SET #tablename = "table";
SET #columnname = "fieldname";
SET #preparedStatement = (SELECT IF(
(
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
WHERE
(table_name = #tablename)
AND (table_schema = #dbname)
AND (column_name = #columnname)
) > 0,
"SELECT 1",
CONCAT("ALTER TABLE ", #tablename, " ADD ", #columnname, " DECIMAL(18,4) NULL;")
));
PREPARE alterIfNotExists FROM #preparedStatement;
EXECUTE alterIfNotExists;
DEALLOCATE PREPARE alterIfNotExists;
This below worked for me:
SELECT count(*)
INTO #exist
FROM information_schema.columns
WHERE table_schema = 'mydatabase'
and COLUMN_NAME = 'mycolumn'
AND table_name = 'mytable' LIMIT 1;
set #query = IF(#exist <= 0, 'ALTER TABLE mydatabase.`mytable` ADD COLUMN `mycolumn` MEDIUMTEXT NULL',
'select \'Column Exists\' status');
prepare stmt from #query;
EXECUTE stmt;
Sometimes it may happen that there are multiple schema created in a database.
So to be specific schema we need to target, so this will help to do it.
SELECT count(*) into #colCnt FROM information_schema.columns WHERE table_name = 'mytable' AND column_name = 'mycolumn' and table_schema = DATABASE();
IF #colCnt = 0 THEN
ALTER TABLE `mytable` ADD COLUMN `mycolumn` VARCHAR(20) DEFAULT NULL;
END IF;
Using this as an example:
https://dbabulletin.com/index.php/2018/03/29/best-practices-using-flyway-for-database-migrations/
DELIMITER $$
DROP PROCEDURE IF EXISTS upgrade_database_4_to_5 $$
CREATE PROCEDURE upgrade_database_4_to_5()
BEGIN
IF NOT EXISTS( (SELECT * FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE()
AND COLUMN_NAME='multi_user' AND TABLE_NAME='settings') ) THEN
ALTER TABLE `settings` ADD COLUMN `multi_user` TINYINT(1) NOT NULL DEFAULT 1;
END IF;
END $$
CALL upgrade_database_4_to_5() $$
DELIMITER ;

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.

MySQL: IF EXISTS ... TRUNCATE

Want to truncate a table if it exists:
IF EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'mytable') TRUNCATE mytable
Error:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'IF EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE
TABLE_NAME = 'mytable') ' at line 1
I tried also to add THEN after ) but the problems seems to be at IF.
You need the two statements below to do that:
create table if not exists <mytable>;
truncate table <mytable>;
So I had a similar issue, and to resolve it, I created this procedure:
DELIMITER $$
DROP PROCEDURE IF EXISTS `truncate_if_exist`$$
CREATE PROCEDURE `truncate_if_exist`(IN tbl_name VARCHAR(150) )
BEGIN
IF EXISTS( SELECT 1 FROM information_schema.TABLES WHERE table_name = tbl_name AND table_schema = DATABASE()) THEN
SET #query = CONCAT('TRUNCATE ', tbl_name);
PREPARE stmt FROM #query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;
END $$
DELIMITER ;
And then called it for each table that I wanted to truncate
for example:
CALL truncate_if_exist('users');
CALL truncate_if_exist('random_tmp_table');
Obviously, if the table does not exist, it will not run the TRUNCATE command.

Create a new MySQL Database from existing db with up to 10000 rows of data from each table

I am trying to create a database with some data not all. I don't need 1M+ records to do what I need so I am okay with only 10000 rows.
I figured I can use a stored procedure to loop through all the table and manually create each table and insert only 10000 rows.
I created a stored procedure like this
CREATE DEFINER=`root`#`10.%` PROCEDURE `createNewDatabase`(in db_name varchar(100), in new_db_name varchar(100))
BEGIN
DECLARE finish INT DEFAULT 0;
DECLARE tbl VARCHAR(100);
DECLARE cur_tables CURSOR FOR SELECT table_name FROM information_schema.tables WHERE table_schema = db_name AND TABLE_TYPE='BASE TABLE';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finish = 1;
OPEN cur_tables;
my_loop: LOOP
FETCH cur_tables INTO tbl;
IF finish = 1 THEN
LEAVE my_loop;
END IF;
SET #str = CONCAT('DROP TABLE IF EXISTS `', new_db_name, '`.`' , tbl , '`; CREATE TABLE `', new_db_name, '`.`' , tbl , '` LIKE `', db_name , '`.`', tbl,'`; INSERT INTO `', new_db_name , '`.`' , tbl, '` SELECT * FROM `', db_name ,'`.`', tbl , '` LIMIT 10000;');
PREPARE stmt FROM #str;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END LOOP;
CLOSE cur_tables;
END
Then I called it like this
CALL createNewDatabase('baseTable', 'newTable');
But I run the procedure I get the following error
Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'CREATE TABLE `newTable`.`account_addresses` LIKE `baseTable`.`account_addres' at line 1
if I added the following 2 lines after just before the prepare statement
SELECT #str;
LEAVE my_loop;
I get the following queries which works if I executed them manually
DROP TABLE IF EXISTS `newTable`.`account_addresses`;
CREATE TABLE `newTable`.`account_addresses` LIKE `baseTable`.`account_addresses`;
INSERT INTO `newTable`.`account_addresses` SELECT * FROM `newTable`.`account_addresses` LIMIT 10000;
CREATE TABLE `newTable`.`account_addresses` LIKE `baseTable`.`account_addresses`; INSERT INTO `newTable`.`account_addresses` SELECT * FROM `baseTable`.`account_addresses` LIMIT 10000;
What am I doing wrong here? Why it is erroring?
Quote from mysql's documentation on PREPARE:
The text must represent a single statement, not multiple statements.
You are trying to execute a drop table and a create table statement, insert records in 1 prepared statement and this is not allowed. Have 3 separate prepared statement for the 3 commands.

Categories