Firstly, my apologies about the sarky comment above.
The reason you receive this error is because your alter script isn't taking any action with respect to constraints. Columns which are the target of constraints (Unique, Foreign Key, Default
, etc) can't be modified unless the constraint is first dropped. In which case you'll probably need to add the constraints back afterwards.
I've assumed your earlier (deleted) comment still holds, viz that you do not require to create the constraints again after they have been dropped.
Re : How do I drop all constraints
Disclaimer : Back up your database before you try this, but the following MIGHT work. It is a destructive one way operation.
declare @sql nvarchar(2000);
while(exists(select 1 from sys.objects WHERE type_desc LIKE '%CONSTRAINT%'))
begin
BEGIN TRY
SELECT TOP 1 @sql=('ALTER TABLE ' + SCHEMA_NAME(schema_id) + '.[' + OBJECT_NAME(parent_object_id)
+ '] DROP CONSTRAINT [' + OBJECT_NAME(OBJECT_ID) + ']')
FROM sys.objects
WHERE type_desc LIKE '%CONSTRAINT%'
ORDER BY NEWID();
exec (@sql);
END TRY
BEGIN CATCH
END CATCH
end;
GO
Rationale: The TRY CATCH
is required because there is no guarantee that we will get the order of dependencies correct when dropping constraints (e.g. FK dependent on PK), so we basically squash the error and try drop another random constraint (ORDER BY NEWID()
)
Reference : Based on this query here, but extended to all constraints