Question

I have a table with data, and I want to change some column to unique, it must to be unique, but I'm worried about have duplicated data in that column and it brings some problems to my database.

I want to know what happen if I change a column to unique that doesn't have unique data, I'll lost some records, just got an error message, or something else?

PS.: I'm using SQL Server

Thanks in advance.

Était-ce utile?

La solution

You just won't be able to add a UNIQUE constraint on a COLUMN with duplicates datas.

In SSMS, the error message is something like that

The CREATE UNIQUE INDEX statement terminated because a duplicate key was found for the object name 'dbo.<Table>' and the index name '<constraintname>'. The duplicate key value is (<NULL>).


Could not create constraint. See previous errors.

So you can be quiet, you won't lose any data.

Autres conseils

alter table YourTable add constraint UX_YourTable_YourColumn unique(YourColumn)

If there is duplicate data, the alter will abort without making any changes.

You can query duplicates like:

select  YourColumn
,       count(*) as DuplicateCount
from    YourTable
group by
        YourColumn
having  count(*) > 1
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top