Unable to create index because of duplicate that doesn't exist?

后端 未结 5 1971
眼角桃花
眼角桃花 2021-02-03 17:19

I\'m getting an error running the following Transact-SQL command:

CREATE UNIQUE NONCLUSTERED INDEX IX_TopicShortName
ON DimMeasureTopic(TopicShortName)


        
相关标签:
5条回答
  • 2021-02-03 17:51

    It should have specified the duplicate key value in the error message. "The duplicate key value is (' ', ' ', ' ') The statement has been terminated. You have duplicate values that need to be addressed.

    0 讨论(0)
  • 2021-02-03 17:52

    It's not that the index already exists, but that there are duplicate values of the TopicShortName field in the table itself. According to the error message the duplicate value is an empty string (it might just be a facet of posting I guess). Such duplicates prevent the creation of a UNIQUE index.

    You could run a query to confirm that you have a duplicate:

    SELECT
        TopicShortName,
        COUNT(*)
    FROM
        DimMeasureTopic
    GROUP BY
        TopicShortName
    HAVING
        COUNT(*) > 1
    

    Presumably in the other database the data are different, and the duplicates are not present.

    0 讨论(0)
  • 2021-02-03 17:59

    The duplicate is in your data, try running this query to find it.

    SELECT TopicShortName, COUNT(*)
    FROM DimMeasureTopic
    GROUP BY TopicShortName
    HAVING COUNT(*) > 1
    
    0 讨论(0)
  • 2021-02-03 18:00

    If you are using code-based migrations, and you rename a property of an entity and you are having an unique index for the property, entity framework will create a new column and trying to add an unique index for the new column but the new column has all null values, therefore it will fail. You need to manually modify the migration code to copy the data from old column before the line to create index.

    0 讨论(0)
  • 2021-02-03 18:07

    It's because you have records in the table already that are not unique (by the sounds of it, 2 records with a blank value in the TopicShortName field).

    So, it's to do with the data, not the index itself.

    0 讨论(0)
提交回复
热议问题