Drop column if exists in SQL Server 2008 r2

和自甴很熟 提交于 2020-12-30 06:17:08

问题


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?


回答1:


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



回答2:


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;


来源:https://stackoverflow.com/questions/51492078/drop-column-if-exists-in-sql-server-2008-r2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!