循环并将非唯一GUID分配给值集



我相信这很容易,但我不能跳过概念化到语法:我有一个特性表,其中一个命名的特性可以填充几行,例如:

[NAME], [GUID]
Fred, NULL
Fred, NULL
Fred, NULL
Tom, Null
Mary, Null
Mary, Null
Mary, Null
Mary, Null

我想做的是为每个名称分配一个GUID:

Fred, {3b26af27-9d42-481c-a8c8-be1819dccda5}
Fred, {3b26af27-9d42-481c-a8c8-be1819dccda5}
Fred, {3b26af27-9d42-481c-a8c8-be1819dccda5}
Tom, {ee64b706-def0-4e5c-a5fd-0c219962042e}
Mary, {fd158f90-9705-4a18-b82c-baca29441401}
Mary, {fd158f90-9705-4a18-b82c-baca29441401}
Mary, {fd158f90-9705-4a18-b82c-baca29441401}
Mary, {fd158f90-9705-4a18-b82c-baca29441401}
DECLARE @tmp TABLE
(
    Name    varchar(30),
    GUID    uniqueidentifier
)
INSERT @tmp
    SELECT  x.Name, NEWID()
    FROM    (SELECT DISTINCT Name FROM MyTable) x
UPDATE MyTable
    SET GUID = tmp.GUID
    FROM MyTable t
    INNER JOIN @tmp tmp ON t.Name = tmp.Name

因为NEWID()直到查询结束才实现,所以您需要暂时实现它。在这里,我使用一个表变量为每个名称存储一个新的GUID(通过在Name上分组),然后使用该表更新最终目的地:

DECLARE @MaterializedGuids TABLE (
    Name varchar(20),
    NewGuid uniqueidentifier
)
INSERT INTO @MaterializedGuids (Name, NewGuid)
SELECT Name, NEWID() FROM YourTable GROUP BY Name

现在你可以使用这个内存表来更新你的永久表:

UPDATE y
SET y.[Guid] = x.[NewGuid]
FROM YourTable y
JOIN @MaterializedGuids x ON x.Name = y.Name

然后查看结果:

SELECT * FROM YourTable

感谢这位神秘的发帖者,他在发布答案几分钟后就删除了答案,这有点奏效:

UPDATE y
SET y.[FEATUREID] = x.[NewGUID]
FROM TRANS_TRAILS_LN y
LEFT OUTER JOIN (
    SELECT DISTINCT TRAILNAME, NEWID() AS NewGuid FROM TRANS_TRAILS_LN GROUP BY TRAILNAME
) x ON x.TRAILNAME = y.TRAILNAME

相关内容

  • 没有找到相关文章

最新更新