更新时间:2023-02-07 11:20:38
可以在sys.key_constraints表中查找约束名称:
You can look up the constraint name in the sys.key_constraints table:
SELECT name
FROM sys.key_constraints
WHERE [type] = 'PK'
AND [parent_object_id] = Object_id('dbo.Student');
如果你不在乎名字,只是想去掉,可以结合使用这个和动态sql:
If you don't care about the name, but simply want to drop it, you can use a combination of this and dynamic sql:
DECLARE @table NVARCHAR(512), @sql NVARCHAR(MAX);
SELECT @table = N'dbo.Student';
SELECT @sql = 'ALTER TABLE ' + @table
+ ' DROP CONSTRAINT ' + name + ';'
FROM sys.key_constraints
WHERE [type] = 'PK'
AND [parent_object_id] = OBJECT_ID(@table);
EXEC sp_executeSQL @sql;
此代码来自 Aaron Bertrand(来源).
This code is from Aaron Bertrand (source).