7

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?

Lukasz Szozda
  • 162,964
  • 23
  • 234
  • 275
  • 1
    . . This would appear to be a bug. Of course, I tend to name indexes as "idx__". That makes it much easier to understand messages with the index name. – Gordon Linoff Jan 09 '19 at 21:55
  • @GordonLinoff Yes, I agree that proper naming convention is crucial. I am just curious why seperate statements are ok while inline version ends with error. I also think it is a bug, but first I want to exclude most obvious reasons :) – Lukasz Szozda Jan 09 '19 at 21:56
  • 1
    What version is your database? As much as I agree this isn't a good naming convention it worked without any issue on my 2014 instance. I don't have anything newer readily available. – Sean Lange Jan 09 '19 at 22:03
  • @SeanLange [demo SQL Server 2014](https://dbfiddle.uk/?rdbms=sqlserver_2014&fiddle=003635e54add02444e3e0ddbcb78cf0f) Now I am pretty sure it is a bug :) – Lukasz Szozda Jan 09 '19 at 22:04
  • 1
    Well that is odd. Worked in 2014 but fails in 2017....seems like a bug to me. – Sean Lange Jan 09 '19 at 22:06

1 Answers1

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.

David Browne - Microsoft
  • 80,331
  • 6
  • 39
  • 67
  • 1
    It was my intention from the beginning but first I always ask for opinion. I will create a case and link to this question. Thanks :) – Lukasz Szozda Jan 09 '19 at 22:06
  • 1
    For future reference: https://feedback.azure.com/forums/908035-sql-server/suggestions/36486877-inline-index-definition-fails-when-index-name-is-t – Lukasz Szozda Jan 09 '19 at 22:16