Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

drop column only if exists in sql

Tags:

sql

mysql

guys i am totally newbie .. what i want is to delete a column in table only if it exists ... any help here is what i know ALTER TABLE MEN DROP COLUMN Lname but how to make if it exists only in sql ??

like image 637
mm gg Avatar asked Apr 06 '17 11:04

mm gg


People also ask

How do you delete a column that exists in SQL?

The column Extension existing in the refreshed list is verification that it exists. To drop the Extensions column, we simply right click on it and delete as before.

How do I drop a column with constraints?

The name of the default constraint might have been automatically generated and hard to predict, so you need to look up the default constraint name first, and then drop the column. Just replace __TableName__ and __ColumnName__ with the appropriate values.

Can we drop column using alter?

ALTER TABLE is used to add, delete/drop or modify columns in the existing table. It is also used to add and drop various constraints on the existing table.


3 Answers

Fixed the syntax error in mIhAwk's answer:

if (exists (SELECT * FROM information_schema.COLUMNS WHERE TABLE_NAME = 'mytable' AND COLUMN_NAME = 'mycolumn')) 
begin
    ALTER TABLE mytable DROP COLUMN mycolumn
end
like image 160
Pylinux Avatar answered Sep 26 '22 01:09

Pylinux


What you want to do is not possible in pure MySQL-syntax. However, if you are using a API or something as back-end in a application. You can do the following.

IF (SELECT COUNT(*) 
          FROM table_name.columns 
          WHERE 
          TABLE_SCHEMA = 'database_name' 
          AND TABLE_NAME = 'table_name' 
          AND COLUMN_NAME = 'column_name'>0)
BEGIN
 ALTER TABLE table_name DROP COLUMN column_name
END
like image 31
Robin Skafte Avatar answered Sep 24 '22 01:09

Robin Skafte


Below code solve your problem.

if (exists (SELECT * FROM information_schema.COLUMNS WHERE TABLE_NAME = 'mytable' AND COLUMN_NAME = 'mycolumn')) 
begin
     ALTER TABLE 'mytable' DROP COLUMN 'mycolumn'
end
like image 32
mIhAwk Avatar answered Sep 23 '22 01:09

mIhAwk