是否将表变量中的值分配给表的每一行



我有一个表(引用表(,它将包含唯一的值(uniqueidentifier类型(。我有200万用户,我需要为这个Reference表中的每个用户生成一个唯一的值。在创建它们时,我希望捕获这些唯一的值,并将它们分配给另一个表(称为user表(中的每个用户。

下面是我的尝试:我创建了一个名为@ReferenceId的表变量。如何获取@ReferenceId并将每个唯一值分配给User表中的单独一行?

create procedure create_reference_ids
@numberOfNewAccounts int
DECLARE @ReferenceIds TABLE (Id uniqueidentifier)
set @numberOfNewAccounts = 2000000
as
begin
while @numberOfNewAccounts > 0
begin
insert into Reference (0,0,@UtcNow,@UtcNow)
OUTPUT Inserted.Id INTO @ReferenceIds
set @numberOfNewAccounts = @numberOfNewAccounts - 1
end
end
exec create_reference_ids

使用merge语句插入用户数量的引用值,并将新的ID输出到一个表变量中,该表变量将新的引用ID链接到现有的用户ID。然后对用户表进行更新。

DECLARE @NewId TABLE (UserId int, ReferenceId int);
-- Using Merge for insert is the only way to get values from columns in the output table which don't exist in the Target table
MERGE INTO dbo.Reference AS Target
USING dbo.[User] AS Source
ON 1 = 0 -- Force an insert regardless
WHEN NOT MATCHED THEN
-- Best practice is to always explicitly name your columns
INSERT (Col1, Col2, Col3, Col4)
VALUES (0, 0, @UtcNow, @UtcNow)
OUTPUT Source.Id, Inserted.Id
INTO @NewId (UserId, ReferenceId);
UPDATE U SET
ReferenceId = I.ReferenceId
FROM dbo.[User] U
INNER JOIN @NewId I on I.UserId = U.Id;

最新更新