0

What I'm trying to do is make a copy of a table using a SELECT INTO statement.

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. 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.

What am I missing here?

Thanks.

0

1 Answer 1

7

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.

From CREATE INDEX (Transact-SQL) on MSDN:

index_name - Is the name of the index. 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.

Sign up to request clarification or add additional context in comments.

8 Comments

Index names don't have to be unique. Constraint names do.
I have two tables in my database with pkGUID as a primary key and when I check the properties, I don't see that SSMS has assigned a different name to either of them
@Tom - pkGUID is the name of a constraint not an index.
@Tom - You are confusing constraints with indexes. A constraint name has to be unique within a database. And index name doesn't. You need to give the primary key constraint a different name to the existing one. I assume SSMS does that.
@Tom - I see two identical index names. Open up the Keys nodes.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.