I am getting following error when deleting a column with constraint in SQL Server 2005.
The object 'DF__PlantRecon__Test' is dependent on column 'Test'.
The column is not part of any key. But it has a default constraint and the constraint has a pre-defined name.
Though I have written code to delete constraint first, it is not working.
- Why doesn't it work?
- What need to be done to make it working?
Note: I need to check whether the constraint exist first.
REFERENCES
- Named CONSTRAINT benefits
- How to drop column with constraint?
- How to drop SQL default constraint without knowing its name?
CODE
IF OBJECT_ID('DF__PlantRecon__Test', 'C') IS NOT NULL BEGIN SELECT 'EXIST' ALTER TABLE [dbo].[PlantReconciliationOptions] drop constraint DF__PlantRecon__Test END IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_NAME ='DF__PlantRecon__Test') BEGIN SELECT 'EXIST' --drop constraint ALTER TABLE [dbo].[PlantReconciliationOptions] drop constraint DF__PlantRecon__Test END IF EXISTS ( SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'[dbo].[PlantReconciliationOptions]') AND name = 'Test') BEGIN --drop column ALTER TABLE [dbo].[PlantReconciliationOptions] DROP COLUMN Test END ALTER TABLE PlantReconciliationOptions ADD Test INT NOT NULL CONSTRAINT DF__PlantRecon__Test DEFAULT 30