Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Drop constraint if exist syntax
Message
 
General information
Forum:
Microsoft SQL Server
Category:
Other
Environment versions
SQL Server:
SQL Server 2005
Miscellaneous
Thread ID:
01547008
Message ID:
01547020
Views:
16
>>>Hi,
>>>
>>>I have been looking on various sites for the code to drop a constraint if I know the name of the constraint. Each site has a different code. I am confused. I would like something that would work on SQL Server 2005 and SQL Server 2008. What would you recommend?
>>>
>>>TIA.
>>>
>>>UPDATE. This is the code that works on my SQL Server 2008. Does it look like the right one?:
>>>
>>>
>>>IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[FK_table_name_fk_field]') 
>>>     AND parent_object_id = OBJECT_ID(N'[dbo].[table_name]'))
>>>	BEGIN
>>>		ALTER TABLE [dbo].[table_name] 
>>>		DROP CONSTRAINT [FK_table_name_fk_field]
>>>	END
>>>
>>
>>I don't think you need an extra check for parent_object_id. I believe the constraint names should be unique across database, not table wise (I'm going to test this quickly).
>
>Yes, I see what you are saying. I just found this code that was checking the table name as well and adopted for my use.
>I figured it can't hurt, right?
>So far in my tests, the syntax works.
>Thank you.

I was actually just adding an extra note (and I updated the thread saying that indeed the constraint is unique for the database, I verified).
If you want to test that this constraint belongs to particular table, this syntax is good.
If it's not broken, fix it until it is.


My Blog
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform