8

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 ??

mm gg
  • 109
  • 1
  • 1
  • 3

5 Answers5

6

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
Pylinux
  • 11,278
  • 4
  • 60
  • 67
4

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
Robin
  • 76
  • 1
  • 6
4

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
mIhAwk
  • 119
  • 1
  • 7
3

As mentioned by others, MySQL does not support DROP COLUMN IF EXISTS, so your best approach is simply to run DROP COLUMN and ignore the error if the column doesn't exist.

A while back I wrote about an approach to simulate DROP COLUMN IF EXISTS using common_schema. That may work for you. Check out the relevant blog post for more details.

Ike Walker
  • 64,401
  • 14
  • 110
  • 109
1

IF EXISTS itself is a solution! The following worked for me for both MySQL & SqlServer -

ALTER TABLE #TempTable DROP COLUMN IF EXISTS [ClientId], [VendorId], [UserId]

It works like a charm for multiple columns too!

Tested it on - mysql Ver 15.1 Distrib 10.1.22-MariaDB, for Win32 (AMD64) & SSMS version 14.0.17254.0

Tushar Walzade
  • 3,737
  • 4
  • 33
  • 56