Quantcast
Channel: SQL Server 2005 drop column with constraints - Stack Overflow
Viewing all articles
Browse latest Browse all 14

Answer by Stealth Rabbi for SQL Server 2005 drop column with constraints

$
0
0

Just to build on Jeremy Stein's answer, I created a stored procedure for this, and set it up so it can be used to delete a column that has or does not have default constraints. It's not real efficient since it's querying sys.columns twice, but it works.

CREATE PROCEDURE [dbo].[RemoveColumnWithDefaultConstraints]     -- Add the parameters for the stored procedure here    @tableName nvarchar(max),     @columnName nvarchar(max)ASBEGIN    -- SET NOCOUNT ON added to prevent extra result sets from    -- interfering with SELECT statements.    SET NOCOUNT ON;    DECLARE @ConstraintName nvarchar(200)    SELECT @ConstraintName = Name     FROM SYS.DEFAULT_CONSTRAINTS     WHERE PARENT_OBJECT_ID = OBJECT_ID(@tableName)         AND PARENT_COLUMN_ID = (SELECT column_id FROM sys.columns WHERE NAME = (@columnName)         AND object_id = OBJECT_ID(@tableName))    IF @ConstraintName IS NOT NULL        EXEC('ALTER TABLE '+ @tableName +' DROP CONSTRAINT '+ @ConstraintName)    IF EXISTS(SELECT * FROM sys.columns WHERE Name = @columnName          AND Object_ID = Object_ID(@tableName))        EXEC('ALTER TABLE '+ @tableName +' DROP COLUMN '+ @columnName)       ENDGO

Viewing all articles
Browse latest Browse all 14

Trending Articles