插入列以在T-SQL中生成主键

时间:2013-08-08 12:11:05

标签: sql-server tsql insert primary-key

我现在有一个庞大的表(超过一百万条记录),目前包含以下两列:CustomerNameAmountBilled

我想添加另一个列,我们可以将其称为PurchaseID,以便CustomerName + PurchaseID成为唯一的组合,因此我可以创建主键。

比如说,我的原始数据如下所示:

CustomerName AmountBilled
-------------------------    
Bill          $2
Bill          $3.5
Joe           $5

我希望我的新表看起来像这样:

Bill    1    $2
Bill    2    $3.5
Joe     1    $5

第二列以SQL计算。

对此有什么正确的SQL声明?

1 个答案:

答案 0 :(得分:2)

alter table TableName
    add PurchaseID int NULL
GO
;with cte as (
  select *, rn = row_number() over (partition by CustomerName order by @@spid)
  from TableName
)
update cte set PurchaseID = rn
GO
alter table TableName
    alter column PurchaseID int not NULL
GO