문제

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.

도움이 되었습니까?

해결책

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.

다른 팁

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top