我确信这很简单,但我不能超越概念化语法:我有一个功能表,其中一个命名功能可以填充多行,例如:
[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}
答案 0 :(得分:1)
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
答案 1 :(得分:0)
由于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
答案 2 :(得分:0)
感谢神秘的海报,他在发布后删除了他的答案,这有点奏效:
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