无法从 table 删除 UNIQUE 索引

Can not drop UNIQUE index from table

当我运行这个查询

ALTER TABLE "dbo"."ROOM" DROP INDEX "UNIQUE";

我收到这条消息:

Error 1018: Incorrect syntax near 'INDEX'. If this is intended as a part of a table hint, A WITH keyword and parenthesis are now required. See SQL Server Books Online for proper syntax.

唯一索引的名称是UNIQUE。我认为这就是问题所在,它是一个自动生成的名称(对于用于创建此索引的 SQL 服务器客户端)。这是创建 table 语句:

CREATE TABLE "ROOM" (
    "ID" BIGINT NOT NULL DEFAULT NULL,
    //the rest of the columns...
    "ROOM" VARCHAR(100),
    UNIQUE INDEX "UNIQUE" ("ROOM")
)
;

知道如何删除该索引吗?我知道我可以删除 table,然后重新创建它,我想避免这种情况。

你需要使用这个语句:

DROP INDEX [UNIQUE] ON dbo.Room 

您需要删除索引,并定义它是在哪个 table 上创建的...并且由于它的名称是保留的 SQL 关键字,您需要将其放在方括号中([UNIQUE]).

有关详细信息,请参阅 official MSDN documentation on DROP INDEX

更新: 如果这个语句不起作用,那么索引 根本就不会被调用 UNIQUE

使用以下语句检查 Room table 上定义了哪些索引:

SELECT * 
FROM sys.indexes 
WHERE object_id=OBJECT_ID('dbo.Room')

并查看 Name 列 - 然后使用 适当的 实际索引名称来删除该索引。

更新 #2: 好的,所以你 确实 有一个唯一约束,它由那个唯一索引强制执行。所以为了摆脱它,首先你需要找出那个约束叫什么,它在哪个 table 上:

SELECT 
    name, 
    TableName = OBJECT_NAME(parent_object_id)
FROM sys.key_constraints
WHERE type = 'UQ'

获得这两条信息后,您现在可以删除该约束:

ALTER TABLE (TableName)
DROP CONSTRAINT (ConstraintName)

然后您的唯一索引也将消失。

第一步,获取索引

select schema_name(t.schema_id) + '.' + t.[name] as table_view, 
    case when t.[type] = 'U' then 'Table'
        when t.[type] = 'V' then 'View'
        end as [object_type],
    case when c.[type] = 'PK' then 'Primary key'
        when c.[type] = 'UQ' then 'Unique constraint'
        when i.[type] = 1 then 'Unique clustered index'
        when i.type = 2 then 'Unique index'
        end as constraint_type, 
    c.[name] as constraint_name,
    substring(column_names, 1, len(column_names)-1) as [columns],
    i.[name] as index_name,
    case when i.[type] = 1 then 'Clustered index'
        when i.type = 2 then 'Index'
        end as index_type
from sys.objects t
    left outer join sys.indexes i
        on t.object_id = i.object_id
    left outer join sys.key_constraints c
        on i.object_id = c.parent_object_id 
        and i.index_id = c.unique_index_id
   cross apply (select col.[name] + ', '
                    from sys.index_columns ic
                        inner join sys.columns col
                            on ic.object_id = col.object_id
                            and ic.column_id = col.column_id
                    where ic.object_id = t.object_id
                        and ic.index_id = i.index_id
                            order by col.column_id
                            for xml path ('') ) D (column_names)
where is_unique = 1
and t.is_ms_shipped <> 1 and t.[name]='table name'
order by schema_name(t.schema_id) + '.' + t.[name]

第二步,drop indexes

DROP INDEX [INDEXES NAME] ON dbo.[TABLE NAME]