Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drop column if exists in SQL Server 2008 r2

I am using SQL Server 2008 R2.

I want to drop the column if it is already exists in the table else not throw any error.

Tried:

ALTER TABLE Emp 
DROP COLUMN IF EXISTS Lname;

Error:

Incorrect syntax near the keyword 'IF'.

By searching I came to know that, this option is available from 2016.

What is the alternative in the SQL Server 2008 R2?

like image 746
MAK Avatar asked Jul 24 '18 06:07

MAK


People also ask

How do I drop a dependent column in SQL Server?

We cannot remove a column with a CHECK constraint in the table. If we want to drop a column with constraints, we first remove the constraint. SQL Server does not drop a column with PRIMARY or FOREIGN KEY constraints or other dependencies. However, we can do this by using the Table Designer.

Can we drop column using alter?

Syntax. The syntax to drop a column in a table in MySQL (using the ALTER TABLE statement) is: ALTER TABLE table_name DROP COLUMN column_name; table_name.


2 Answers

IF EXISTS (SELECT 1
               FROM   INFORMATION_SCHEMA.COLUMNS
               WHERE  TABLE_NAME = 'Emp'
                      AND COLUMN_NAME = 'Lname'
                      AND TABLE_SCHEMA='DBO')
  BEGIN
      ALTER TABLE Emp
        DROP COLUMN Lname
  END
GO
like image 137
Chanukya Avatar answered Oct 27 '22 00:10

Chanukya


From the MSDN social documentation, we can try:

IF EXISTS (SELECT 1 FROM sys.objects o
          INNER JOIN sys.columns c ON o.object_id = c.object_id
          WHERE o.name = 'Emp' AND c.name = 'Lname')
ALTER TABLE dbo.Emp DROP COLUMN Lname;
like image 29
Tim Biegeleisen Avatar answered Oct 26 '22 23:10

Tim Biegeleisen