Wednesday, December 06, 2006

SQL Server Deleting column hell

It is really interesting, but common that the most simple things, are the hardest to make, or  fix :)

I was really surprised that such a simple operation like deleting column from the table in SQL server is not easy to do. Well it is easy to create it, but to remove it a little hack can be used.

-- declares script for query and name of the column constraint name
DECLARE @defname VARCHAR(100), @cmd VARCHAR(1000)

-- get selected column constraint name
SET @defname = (     
           SELECT   c_obj.name
           FROM      sysobjects c_obj
                           join sysobjects t_obj     ON c_obj.parent_obj = t_obj.id
                           join sysconstraints con ON c_obj.id = con.constid
                           join syscolumns col       ON t_obj.id = col.id
                           AND con.colid = col.colid
           WHERE
                           c_obj.uid = user_id()
                           AND  c_obj.xtype = 'D'
                           AND  t_obj.name = 'Countries'
                           AND  col.name = 'Code' )
-- build sql query string
SET @cmd = 'ALTER TABLE P_Product DROP CONSTRAINT ' + @defname

--execute it
EXEC( @cmd )

In this sample, the column Code is deleted from the table Countries.
The actual problem is related to default constraint that is created, if you don't specify default constraint name when creating new column.

This link was really helpfull, but it took me so much time to find :(
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnsqlpro2k/html/sql00a11.asp

I hope it would help someone out there :)