为列中的每一行生成guid

时间:2013-07-24 16:10:57

标签: sql sql-server tsql

我有一个包含一列表的存储过程,我需要为该列中的每一行生成一个NEWID()。我是否只能通过循环实现这一目标?

+---+    +--------------------------------------+---+
| a |    | FD16A8B5-DBE6-46AB-A59A-6B6674E9A78D | a |
| b | => | 9E4A6EE6-1C95-4C7F-A666-F88B32D24B59 | b |
| c |    | 468C0B23-5A7E-404E-A9CB-F624BDA476DA | c |
+---+    +--------------------------------------+---+

3 个答案:

答案 0 :(得分:7)

您应该可以从表格中进行选择并添加newid()以生成每行的值:

select newid(), col
from yourtable;

请参阅SQL Fiddle with Demo

答案 1 :(得分:4)

您可以使用新guid

创建列
alter table yourtable add id varchar(40) not null default NEWID() 

http://sqlfiddle.com/#!3/b3c31/1

答案 2 :(得分:0)

newid()肯定会起作用。但也会产生“支离破碎”的价值观。

根据您的需要,这可能是有益的或有害的(认为是主要关键)。

这是一段程序,我写了一段时间回到“有点帮助”碎片。

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[uspNewSequentialUUIDCreateSingle]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[uspNewSequentialUUIDCreateSingle]
GO

/*

--START TEST

declare @returnCode int
declare @ReturnUUID uniqueidentifier

EXEC @returnCode = dbo.uspNewSequentialUUIDCreateSingle @ReturnUUID output
print @ReturnUUID
print '/@returnCode/'
print @returnCode


--loop test,,,loop exists for TESTING only fyi

declare @counter int
select @counter = 1000

while @counter > 0
    begin
        EXEC @returnCode = dbo.uspNewSequentialUUIDCreateSingle @ReturnUUID output
        print @ReturnUUID
        select @counter = @counter - 1
    end


--END TEST CODE


*/

CREATE PROCEDURE [dbo].[uspNewSequentialUUIDCreateSingle] (
@ReturnUUID uniqueidentifier output  --return
)

AS


--//You can use NEWSEQUENTIALID() to generate GUIDs to reduce page contention at the leaf level of indexes.

SET NOCOUNT ON 

--      declare @ReturnUUID uniqueidentifier

declare @t table ( id int , uuid uniqueidentifier default newsequentialid() )
insert into @t ( id ) values (0)
select @ReturnUUID = uuid from @t



SET NOCOUNT OFF
GO

GRANT EXECUTE ON dbo.uspNewSequentialUUIDCreateSingle TO public

GO