7

我有一个存储过程,它有一个包含一列的表,我需要为该列中的每一行生成一个 NEWID()。我只能通过循环来完成吗?

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

3 回答 3

9

您应该能够从表中进行选择并包含newid()以生成每一行的值:

select newid(), col
from yourtable;

请参阅带有演示的 SQL Fiddle

于 2013-07-24T16:14:54.033 回答
7

您可以使用新的 guid 创建一个列

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

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

于 2013-07-24T16:23:57.780 回答
0

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

这可能对您的需求有益或有害(将 guid 视为主键)。

这是我不久前写的一个程序,用于处理碎片的“有点帮助”。

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
于 2013-07-24T17:38:18.187 回答