Monday, 2 February 2009

Add/Drop column in SQL Server

Add new column to existing table

IF NOT EXISTS( SELECT 1 FROM information_schema.columns WHERE table_name = 'table_name' AND column_name = 'column_name' )
BEGIN
  ALTER TABLE table_name ADD column_name VARCHAR(255) NULL
END
GO

Remove column from the table

IF EXISTS( SELECT 1 FROM information_schema.columns WHERE table_name = 'table_name' AND column_name = 'column_name' )
BEGIN
  ALTER TABLE table_name DROP COLUMN column_name
END
GO

No comments:

Post a Comment