Inline index definition fails when name is the same as table name

时间:2019-01-09 21:51:08

标签: sql sql-server tsql create-table sql-server-2017

SQL Server objects i.e. tables and indexes have their own namespaces. So it is possible to have the same name for index and table(but it's not a common/good practice):

CREATE TABLE t(id INT PRIMARY KEY, col INT);
CREATE INDEX t ON t(col);

SELECT * FROM sys.tables WHERE name = 't';
SELECT * FROM sys.indexes WHERE name = 't';

db<>fiddle demo

Unfortunately I am not able to create the same construct using inline index definition:

CREATE TABLE t(id INT PRIMARY KEY, col INT, INDEX t(col));

Msg 2714 Level 16 State 5 Line 1

There is already an object named 't' in the database.

-- below code is working correctly
CREATE TABLE t(id INT PRIMARY KEY, col INT, INDEX t1(col));

db<>fiddle demo 2

Do I miss something obvious or is it a bug?

1 个答案:

答案 0 :(得分:6)

Do I miss something obvious or is it a bug?

Looks like a bug.

CREATE TABLE t(id INT PRIMARY KEY, col INT, INDEX t(col));

outputs

Microsoft SQL Server 2017 (RTM-GDR) (KB4293803) - 14.0.2002.14 (X64) 
    Jul 21 2018 07:47:45 
    Copyright (C) 2017 Microsoft Corporation
    Developer Edition (64-bit) on Windows 10 Enterprise 10.0 <X64> (Build 17763: ) (Hypervisor)


(1 row affected)

Msg 2714, Level 16, State 5, Line 4
There is already an object named 't' in the database.
Msg 1750, Level 16, State 1, Line 4
Could not create constraint or index. See previous errors.

Please add a feedback item here: https://feedback.azure.com/forums/908035-sql-server Especially noting that this is a regression in SQL 2016.