如果我不知道它的名字,如何删除表PK

时间:2013-12-11 13:58:13

标签: sql-server sql-server-2008 sql-server-2008-r2

我尝试删除主键:

alter table mytable DROP (
 SELECT CONSTRAINT_NAME FROM information_schema.table_constraints
 where table_name='mytable' and constraint_type = 'PRIMARY KEY')

如何正确地做到这一点?

1 个答案:

答案 0 :(得分:2)

首先,don't use INFORMATION_SCHEMA views。其次,DDL或DML中的always use the schema prefix when referencing objects。第三,您需要使用动态SQL,因为您无法以这种方式参数化DDL。

DECLARE @sql NVARCHAR(MAX);

SELECT @sql = N'ALTER TABLE dbo.mytable DROP CONSTRAINT ' 
  + QUOTENAME(k.name) + ';'
    FROM sys.key_constraints k
INNER JOIN sys.objects AS o
ON k.parent_object_id = o.[object_id]
INNER JOIN sys.schemas AS s
ON o.[schema_id] = s.[schema_id]
WHERE o.name = N'mytable'
AND s.name = N'dbo';

PRINT @sql;
-- EXEC sp_executesql @sql;

现在,这不一定有效,例如,如果有其他表引用此主键的外键,则需要先找出它们并先修复它们。