开发者

how to set unique id to each row in a column on SQL Server

开发者 https://www.devze.com 2023-01-06 09:05 出处:网络
Is there a way to set some column of each row in a table to so开发者_如何学Cme unique value e.g.

Is there a way to set some column of each row in a table to so开发者_如何学Cme unique value e.g.

update mytable set myCol=rownum() 

using SQL (not T/SQL) on SQL Server 2000. I can't touch the schema but I do have a spare column or two.


Provided that you have a primary key, you can generate a unique value by counting rows. For example (replace #t with your table's name):

update  t
set     t.col1 = (select COUNT(*) from #t t2 where t.pk >= t2.pk)
from    #t t

If you have a varchar(36) or larger, you can generate GUID's, which are guaranteed to be unique:

update  #t
set     col1 = NEWID()

If you have neither, you can use a variable. This technique is frowned upon because it's not set based, but it works pretty well:

declare @i int
set @i = 1

update  #t
set     col1 = @i
,       @i = @i + 1
0

精彩评论

暂无评论...
验证码 换一张
取 消