如何为SQL Server上的列中的每一行设置唯一ID

mik*_*may 3 sql-server

有没有办法将表中每行的某些列设置为某个唯一值,例如

update mytable set myCol=rownum() 
Run Code Online (Sandbox Code Playgroud)

在SQL Server 2000上使用SQL(而不是T/SQL).我无法触摸架构,但我确实有一两个备用列.

And*_*mar 8

如果您有主键,则可以通过计算行来生成唯一值.例如(替换#t为您的表名):

update  t
set     t.col1 = (select COUNT(*) from #t t2 where t.pk >= t2.pk)
from    #t t
Run Code Online (Sandbox Code Playgroud)

如果你有一个varchar(36)或更大,你可以生成GUID,保证是唯一的:

update  #t
set     col1 = NEWID()
Run Code Online (Sandbox Code Playgroud)

如果您没有,则可以使用变量.这种技术不受欢迎,因为它没有基于设置,但它运作良好:

declare @i int
set @i = 1

update  #t
set     col1 = @i
,       @i = @i + 1
Run Code Online (Sandbox Code Playgroud)