协调类似的标识符,使它们成为SQL Server 2008的主键

时间:2012-07-30 19:48:20

标签: sql sql-server tsql

有关示例数据,请参阅下面的屏幕截图。归一化这些数据我发现这些类似的代码就我的数据而言意味着相同的东西。我正在尝试更新我的表格,以便右侧的primarycode更新为左侧的{/ 1}}

enter image description here

我用来查找这些值的查询:

select  *
from icd
inner join icd as i2 on i2.primarycodetext=icd.primarycodetext
and i2.primarycode <> icd.primarycode
where icd.primarycode like '%0'

我试过的更新查询。

update icd
set icd.primarycode=i2.primarycode
from 
(


select  *
from icd
inner join icd as i2 on i2.primarycodetext=icd.primarycodetext
and i2.primarycode <> icd.primarycode
where icd.primarycode like '%0'
)t

收到的错误:Msg 8156, Level 16, State 1, Line 12 The column 'primarycode' was specified multiple times for 't'. 编辑:此表中只有两列是primarycode和primarycodetext

1 个答案:

答案 0 :(得分:2)

好的,对于您的问题,您应该执行以下操作:

UPDATE I1
SET I1.primarycode = I2.primarycode
FROM icd AS I1
INNER JOIN icd AS I2 
ON i2.primarycodetext = i1.primarycodetext
AND i2.primarycode <> I1.primarycode
WHERE I1.primarycode LIKE '%0'

但是这样做后你的桌子上会有重复的东西。想一想你真正想要得到什么(这些值的唯一记录),那么你应该DELETE这些记录而不是更新它们:

DELETE I1
FROM icd AS I1
INNER JOIN icd AS I2 
ON i2.primarycodetext = i1.primarycodetext
AND i2.primarycode <> I1.primarycode
WHERE I1.primarycode LIKE '%0'