2016-10-03 92 views
1

我想更新我的临时表记录。但我现有的临时表没有任何独特的列。所以我需要添加标识列并更新基于该标识列的所有记录。SQL - 在现有临时表中追加标识列

例如,如果我的临时表有1000个没有任何唯一列值的记录。我需要对所有这1000个记录进行编号并更新值。

while(@count < identity_value) 
begin 
update #temp 
Name = 'Gold' 
where identity = @count 
@count = @count+1 
End 

我可以改变表选项,但在我的情况下,记录已经插入到我的临时表中。所以我需要通过添加Identity列来循环播放。

+0

的可能的复制[列添加到现有的表并唯一它们编号](http://stackoverflow.com/questions/108211/add-a-column-to-existing-table -and-unique-number-them) –

+0

因此,添加标识列的唯一原因是您可以单独通过并更新每一行?为什么不使用'update #temp set Name ='Gold''? –

回答

2

有没有必要做一个UPDATE。标识列将在创建时填充。所有你需要的是:

ALTER TABLE #temp 
ADD Id INT Identity(1, 1) 
GO 

Id字段将被填充,将举办值1, 2, ..., 1000

0

你不需要循环。看到这个简化的例子:

CREATE TABLE #temp 
(
    Name varchar(10) 
) 
INSERT #temp VALUES ('A'),('B') 

--Add identity column 
ALTER TABLE #temp ADD ID int IDENTITY