2013-08-23 42 views
0

我有一个包含数据的表,我想将某些列更改为唯一,但它必须是唯一的,但我担心该列中存在重复的数据,并且会给我的数据库带来一些问题。将列更改为唯一

我想知道如果将列更改为不具有唯一数据的唯一列,会丢失一些记录,只是收到错误消息或其他内容会发生什么?

PS .:我正在使用SQL Server

在此先感谢。

回答

0

你只是将无法在列添加UNIQUE约束与重复DATAS。

在SSMS,该错误信息是类似的东西

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. 

所以,你可以安静的,你不会丢失任何数据。

0
alter table YourTable add constraint UX_YourTable_YourColumn unique(YourColumn) 

如果有重复的数据,alter将中止不做任何更改。

您可以查询像重复:

select YourColumn 
,  count(*) as DuplicateCount 
from YourTable 
group by 
     YourColumn 
having count(*) > 1 
+0

他说“有重复的数据在该列”? –

+0

我不是在寻找sql代码,我需要知道如果我执行alter table会发生什么。 – guisantogui