【发布时间】:2017-03-10 22:35:08
【问题描述】:
我正在尝试删除一些在我在某处添加默认值时自动生成的约束。
我使用以下脚本返回约束的名称:
SELECT default_constraints.name FROM sys.all_columns
INNER JOIN sys.tables ON all_columns.object_id = tables.object_id
INNER JOIN sys.schemas ON tables.schema_id = schemas.schema_id
INNER JOIN sys.default_constraints ON all_columns.default_object_id = default_constraints.object_id
WHERE tables.name = 'TrainingType'
AND default_constraints.name like 'DF__TrainingT__Soft__%'
OR default_constraints.name like 'DF__TrainingT__EndUs__%'
OR default_constraints.name like 'DF__TrainingC__Compu__%'
这会返回以下内容:
| name
---------------------------------
1 | DF__TrainingC__Compu__2058C9F1
2 | DF__TrainingT__EndUs__1559B68C
3 | DF__TrainingT__Softw__05CD5A39
现在我正在尝试使用这些值删除约束,但它不允许我这样做 DROP CONSTRAINT ( ... )
ALTER TABLE TrainingType
DROP CONSTRAINT (
SELECT default_constraints.name FROM sys.all_columns
INNER JOIN sys.tables ON all_columns.object_id = tables.object_id
INNER JOIN sys.schemas ON tables.schema_id = schemas.schema_id
INNER JOIN sys.default_constraints ON all_columns.default_object_id = default_constraints.object_id
WHERE tables.name = 'TrainingType'
AND default_constraints.name like 'DF__TrainingT__Soft__%'
OR default_constraints.name like 'DF__TrainingT__EndUs__%'
OR default_constraints.name like 'DF__TrainingC__Compu__%'
)
那么我怎样才能正确地放弃约束呢?
【问题讨论】:
-
带动态sql
-
当您尝试注入动态限定符时,drop 约束需要一个静态限定符。
-
@SqlZim 你的意思是使用
EXEC? -
@RossBush 我完全知道这一点,但我永远不会知道静态限定符,因为它每天都会改变并在后面得到一个随机数
标签: sql sql-server constraints