how to drop column from table if exists - mysql

This is the query i am using:
IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME =( N'CustomerVariable1Value'))
begin Alter table temp.DIM_BE_ACCOUNT drop column CustomerVariable1Value
It works fine the first time but when I run it again, it shows error.
How to make it error free and executes it many number of times?
Error message:
ALTER TABLE DROP COLUMN failed because column 'CustomerVariable1Value' does not exist in table 'DIM_BE_ACCOUNT'.

You are only looking for a column name out of all column names in the entire MySQL instance. You need to also filter by schema (=database) and table names:
IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME = N'CustomerVariable1Value' AND TABLE_NAME = 'MyTableName' AND TABLE_SCHEMA = 'MyDatabase')

Here is a solution that does not involve querying INFORMATION_SCHEMA, it simply ignores the error if the column does not exist.
DROP PROCEDURE IF EXISTS `?`;
DELIMITER //
CREATE PROCEDURE `?`
(
)
BEGIN
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION BEGIN END;
ALTER TABLE `table_name` DROP COLUMN `column_name`;
END //
DELIMITER ;
CALL `?`();
DROP PROCEDURE `?`;
P.S. Feel free to give it other name rather than ?

Related

How to execute a stored statement in a stored procedure

I'm creating a function in mySQL that will update table metrics each time the any table has something inserted or deleted from it. So I've got my Table_metrics table, with elements table_name and row_count:
CREATE TABLE Table_metrics (
table_name VARCHAR(64),
row_count INTEGER DEFAULT 0 );
So any time something gets added to any of my tables (other than this one) in the database the matching row gets updated with the number of rows in that table.
To do this I've tried making a stored procedure:
CREATE PROCEDURE table_update_metric(IN tablename VARCHAR(64))
UPDATE Table_metrics
SET row_count=(SELECT COUNT(*) FROM tablename)
WHERE table_name = tablename;
This produces an error when I call the procedure call table_update_metric('Owners'); (Owners being a table in my database)
table DB.tablename doesn't exist
I've done a bit of digging into stored procedures, trying to figure out how they would work. I assume the issue is coming from the line `SELECT COUNT(*) FROM tablename), so I tried having a stored statement in the procedure:
CREATE PROCEDURE table_update_metric(IN TABLENAME VARCHAR(64))
SET #s = CONCAT('SELECT COUNT(*) FROM ', tablename)
UPDATE Table_metrics
SET row_count=EXECUTE #s
WHERE table_name = tablename;
I'm not really sure how to properly do a stored statement as I'm still relatively new to mySQL, but I believe that it's the way to go.
Can anyone offer any insight into this problem?
What you are trying to do is already provided in Mysql. Information Schema Tables stores this information for you :)
SELECT TABLE_NAME, TABLE_ROWS)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = '{your_db}';
From what Somonare said, I created a table in my database that uses that information:
CREATE TABLE Table_metrics
SELECT TABLE_NAME, TABLE_ROWS FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'Sensors';
And this table will be updated with a trigger each time the tables in Sensors are updated.

Procedure run time

DELIMITER $
DROP PROCEDURE IF EXISTS CREATE_BACKUP$
CREATE PROCEDURE CREATE_BACKUP()
BEGIN
DECLARE BACK INT DEFAULT 0;
SELECT TABLE_NAME
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = 'STUDENTDB'
;
SHOW_LOOP:LOOP
IF BACK = 1
THEN
LEAVE SHOW_LOOP;
END IF;
CREATE TABLE STUDENT_BACKUP
AS SELECT * FROM STUDENT;
CREATE TABLE SCORE_BACKUP
AS SELECT * FROM SCORE;
CREATE TABLE GRADE_EVENT_BACKUP
AS SELECT * FROM grade_event;
END LOOP SHOW_LOOP;
END$
DELIMITER ;
Hi, when I run this procedure, it runs more than one time. So I get an error which says "STUDENT_BACKUP table already exists" for the second time when it runs. What should I do to run it just 1 time?
In MySQL you can use CREATE TABLE IF NOT EXIST... to avoid the error occurrence. See CREATE TABLE syntax for details.
To solve your quesrion for SQL server use an INFORMATION_SCHEMA view. A similar solution is in the existing topic.

how to write DDL command inside a procedure for checking and adding column in a table?

How to create a procedure which will check the particular column is present in table or not
If not then I want to add that column in that table using ddl command
you can use this code in a stored procedure:
IF EXISTS(SELECT * FROM sys.columns
WHERE Name = N'yourColumnName' AND Object_ID = Object_ID(N'yourTableName'))
BEGIN
-- your column exists
END
ELSE
BEGIN
--Add column
END

Update MySQL database table schema

I want to update a MySQL database schema (with MySQL code) but I am unfortunately not sure of the state of the tables, as they are distributed..
Let's say some 'clients' have a table called "user" with a schema like
name VARCHAR(64) NOT NULL
password VARCHAR(64) NOT NULL
I want to add an email column, but it's possible that they already have an email column (depending on their installation version).
How can I run a command that ensures that there is a email column and does nothing if it's already there? Keep in mind I would be doing this for many tables that are more complex.
I know I could be creating temp tables and re-populating (and will if it's the only solution) but I figure there might be some kind of CREATE or UPDATE table command that has "oh you already have that column, skip" logic.
You can try like this:
DELIMITER $$
CREATE PROCEDURE Alter_MyTable()
BEGIN
DECLARE _count INT;
SET _count = ( SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'user' AND
COLUMN_NAME = 'email');
IF _count = 0 THEN
ALTER TABLE user
ADD COLUMN email varchar(512);
END IF;
END $$
DELIMITER ;
or rather make it a generic stored procedure like this:
create procedure AddColumnIfDoesntExists(
IN dbName tinytext,
IN tableName tinytext,
IN fieldName tinytext,
IN fieldDef text)
begin
IF NOT EXISTS (
SELECT * FROM information_schema.COLUMNS
WHERE column_name=fieldName
and table_name=tableName
and table_schema=dbName
)
THEN
set #ddl=CONCAT('ALTER TABLE ',dbName,'.',tableName,
' ADD COLUMN ',fieldName,' ',fieldDef);
prepare stmt from #ddl;
execute stmt;
END IF;
end;
//
delimiter ';'
If the column already exists the ALTER TABLE ADD COLUMN statement will throw an error, so if you are thinking that you might lose data because of trying to add a column that already exists that won't be the case, if any you need to handle error. See add column to mysql table if it does not exist
There are also resources telling you how to deal with these with store procedures, etc. See MySQL add column if not exist.
Hope it helps.

Using ALTER to drop a column if it exists in MySQL

How can ALTER be used to drop a column in a MySQL table if that column exists?
I know I can use ALTER TABLE my_table DROP COLUMN my_column, but that will throw an error if my_column does not exist. Is there alternative syntax for dropping the column conditionally?
I'm using MySQL version 4.0.18.
For MySQL, there is none: MySQL Feature Request.
Allowing this is arguably a really bad idea, anyway: IF EXISTS indicates that you're running destructive operations on a database with (to you) unknown structure. There may be situations where this is acceptable for quick-and-dirty local work, but if you're tempted to run such a statement against production data (in a migration etc.), you're playing with fire.
But if you insist, it's not difficult to simply check for existence first in the client, or to catch the error.
MariaDB also supports the following starting with 10.0.2:
DROP [COLUMN] [IF EXISTS] col_name
i. e.
ALTER TABLE my_table DROP IF EXISTS my_column;
But it's arguably a bad idea to rely on a non-standard feature supported by only one of several forks of MySQL.
There is no language level support for this in MySQL. Here is a work-around involving MySQL information_schema meta-data in 5.0+, but it won't address your issue in 4.0.18.
drop procedure if exists schema_change;
delimiter ';;'
create procedure schema_change() begin
/* delete columns if they exist */
if exists (select * from information_schema.columns where table_schema = schema() and table_name = 'table1' and column_name = 'column1') then
alter table table1 drop column `column1`;
end if;
if exists (select * from information_schema.columns where table_schema = schema() and table_name = 'table1' and column_name = 'column2') then
alter table table1 drop column `column2`;
end if;
/* add columns */
alter table table1 add column `column1` varchar(255) NULL;
alter table table1 add column `column2` varchar(255) NULL;
end;;
delimiter ';'
call schema_change();
drop procedure if exists schema_change;
I wrote some more detailed information in a blog post.
I know this is an old thread, but there is a simple way to handle this requirement without using stored procedures. This may help someone.
set #exist_Check := (
select count(*) from information_schema.columns
where TABLE_NAME='YOUR_TABLE'
and COLUMN_NAME='YOUR_COLUMN'
and TABLE_SCHEMA=database()
) ;
set #sqlstmt := if(#exist_Check>0,'alter table YOUR_TABLE drop column YOUR_COLUMN', 'select ''''') ;
prepare stmt from #sqlstmt ;
execute stmt ;
Hope this helps someone, as it did me (after a lot of trial and error).
I just built a reusable procedure that can help making DROP COLUMN idempotent:
-- column_exists:
DROP FUNCTION IF EXISTS column_exists;
DELIMITER $$
CREATE FUNCTION column_exists(
tname VARCHAR(64),
cname VARCHAR(64)
)
RETURNS BOOLEAN
READS SQL DATA
BEGIN
RETURN 0 < (SELECT COUNT(*)
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA` = SCHEMA()
AND `TABLE_NAME` = tname
AND `COLUMN_NAME` = cname);
END $$
DELIMITER ;
-- drop_column_if_exists:
DROP PROCEDURE IF EXISTS drop_column_if_exists;
DELIMITER $$
CREATE PROCEDURE drop_column_if_exists(
tname VARCHAR(64),
cname VARCHAR(64)
)
BEGIN
IF column_exists(tname, cname)
THEN
SET #drop_column_if_exists = CONCAT('ALTER TABLE `', tname, '` DROP COLUMN `', cname, '`');
PREPARE drop_query FROM #drop_column_if_exists;
EXECUTE drop_query;
END IF;
END $$
DELIMITER ;
Usage:
CALL drop_column_if_exists('my_table', 'my_column');
Example:
SELECT column_exists('my_table', 'my_column'); -- 1
CALL drop_column_if_exists('my_table', 'my_column'); -- success
SELECT column_exists('my_table', 'my_column'); -- 0
CALL drop_column_if_exists('my_table', 'my_column'); -- success
SELECT column_exists('my_table', 'my_column'); -- 0
Chase Seibert's answer works, but I'd add that if you have several schemata you want to alter the SELECT thus:
select * from information_schema.columns where table_schema in (select schema()) and table_name=...
You can use this script, use your column, schema and table name
IF EXISTS (SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'TableName' AND COLUMN_NAME = 'ColumnName'
AND TABLE_SCHEMA = SchemaName)
BEGIN
ALTER TABLE TableName DROP COLUMN ColumnName;
END;
Perhaps the simplest way to solve this (that will work) is:
CREATE new_table AS SELECT id, col1, col2, ... (only the columns you actually want in the final table)
FROM my_table;
RENAME my_table TO old_table, new_table TO my_table;
DROP old_table;
Or keep old_table for a rollback if needed.
This will work but foreign keys will not be moved. You would have to re-add them to my_table later; also foreign keys in other tables that reference my_table will have to be fixed (pointed to the new my_table).
Good Luck...
I realise this thread is quite old now, but I was having the same problem.
This was my very basic solution using the MySQL Workbench, but it worked fine...
get a new sql editor and execute SHOW TABLES to get a list of your tables
select all of the rows, and choose copy to clipboard (unquoted) from the context menu
paste the list of names into another editor tab
write your query, ie ALTER TABLE x DROP a;
do some copying and pasting, so you end up with separate query for each table
Toggle whether the workbench should stop when an error occurs
Hit execute and look through the output log
any tables which had the table now haven't
any tables which didn't will have shown an error in the logs
then you can find/replace 'drop a' change it to 'ADD COLUMN b INT NULL' etc and run the whole thing again....
a bit clunky, but at last you get the end result and you can control/monitor the whole process and remember to save you sql scripts in case you need them again.