简体   繁体   English

使用T-SQL创建索引会返回索引存在错误

[英]Creating indexes with T-SQL returns index exists error

What I'm trying to do is make a copy of a table using a SELECT INTO statement. 我想做的是使用SELECT INTO语句制作表的副本。

After the table is created I want to duplicate the indexes as well. 创建表后,我也想复制索引。

So the code I'm using is as follows: 所以我使用的代码如下:

SELECT * INTO TableCopy FROM Table

Then: 然后:

ALTER TABLE TableCopy ADD CONSTRAINT pkGUID PRIMARY KEY ([GUID])
CREATE INDEX ixIndexName ON TableCopy (CountryCode)

When I execute the index SQL, I get an error that the indexes already exist in the catalog. 当执行索引SQL时,出现错误,表明目录中已经存在索引。 I didn't think index names had to be unique, I thought they could be duplicated across different tables. 我认为索引名称不必唯一,我认为它们可以在不同的表中重复。

And lo and behold if I create the indexes through management studio, it accepts the index names. 瞧,如果我通过Management Studio创建索引,它会接受索引名称。

What am I missing here? 我在这里想念什么?

Thanks. 谢谢。

I didn't think index names had to be unique, I thought they could be duplicated across different tables. 我认为索引名称不必唯一,我认为它们可以在不同的表中重复。

No. They do have to be unique within a table/view. 否。它们在表/视图中必须是唯一的。

When you execute within SSMS, it drops the existing index and creates a new one. 在SSMS中执行时,它将删除现有索引并创建一个新索引。

From CREATE INDEX (Transact-SQL) on MSDN: 从MSDN上的CREATE INDEX(Transact-SQL)

index_name - Is the name of the index. index_name-是索引的名称。 Index names must be unique within a table or view but do not have to be unique within a database. 索引名称在表或视图中必须唯一,但在数据库中不必唯一。

(emphasis mine) (强调我的)


However, pkGUID is not an index - it is a constraint , and these do have to be unique within a database. 但是, pkGUID不是索引-它是一个约束 ,并且这些在数据库中必须是唯一的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM