geht hier meine eigene Version, die alle abhängigen Einschränkungen fällt - Standardeinschränkung (falls vorhanden) und alle Check-Einschränkungen betroffen (wie SQL-Standard scheint darauf hinzudeuten und wie einige andere Datenbanken scheinen so)
declare @constraints varchar(4000);
declare @sql varchar(4000);
with table_id_column_position as (
select object_id table_id, column_id column_position
from sys.columns where object_id is not null and object_id = object_id('TableName') and name = 'ColumnToBeDropped'
)
select @constraints = coalesce(@constraints, 'constraint ') + '[' + name + '], '
from sysobjects
where (
-- is CHECK constraint
type = 'C'
-- dependeds on the column
and id is not null
and id in (
select object_id --, object_name(object_id)
from sys.sql_dependencies, table_id_column_position
where object_id is not null
and referenced_major_id = table_id_column_position.table_id
and referenced_minor_id = table_id_column_position.column_position
)
) OR (
-- is DEFAULT constraint
type = 'D'
and id is not null
and id in (
select object_id
from sys.default_constraints, table_id_column_position
where object_id is not null
and parent_object_id = table_id_column_position.table_id
and parent_column_id = table_id_column_position.column_position
)
);
set @sql = 'alter table TableName drop ' + coalesce(@constraints, '') + ' column ColumnToBeDropped';
exec @sql
(Vorsicht: beide TableName
und ColumnToBeDropped
erscheinen zweimal im Code oben)
Dies funktioniert, indem einzelne ALTER TABLE TableName DROP CONSTRAINT c1, ..., COLUMN ColumnToBeDropped
und Ausführung der Konstruktion.
+1 Vielen Dank. Dies funktioniert auch in SQL 2012. – gotqn
Die erste Abfrage funktionierte toll in SQL 2008 R2, als ich die Objekt-ID der Tabelle zuerst mit 'DECLARE @ParentObjectId INT = (wählen Sie OBJECT_ID aus sys.objects wo Name = 'ParentTable' UND Typ = 'U')' und hinzugefügt 'WHERE parent_object_id = @ ParentObjectId' für die Abfrage. Andernfalls erhalten Sie alle Standardeinschränkungen in der Datenbank. – Torrents
Das ist nett, aber es zeigt nicht das Schema, in dem die Tabellen sind. Es wäre nett, wenn Sie eine Verknüpfung zu sys.schemas hinzufügen würden. – AperioOculus