首页 > 解决方案 > 如何为具有不同键的一组记录生成唯一标识符?

问题描述

我有一个如下所示的记录集:

| key_sk | unique_id                            |
|--------|--------------------------------------|
| 2      | null                                 |
| 2      | null                                 |
| 3      | 83a1c90b-e58d-4db4-b438-a79edfb28e60 |
| 3      | 83a1c90b-e58d-4db4-b438-a79edfb28e60 |
| 4      | 4ce66783-0b84-4e8a-a0de-c3284e4d9cd0 |
| 5      | null                                 |

我想为每个为空的唯一key_sk集生成一个唯一ID。unique_id对于上述内容,我想要key_sk 2一个unique_id喜欢key_sk 3的。

uniqueidentifier我在下面的尝试为每组产生了不同的结果。我认为这是因为公用表表达式的递归性质:每次加入 CTE 都会导致NEWID()被调用。

;with update_id_cte as
(
  select distinct hr.key_sk
        ,NEWID() as gened_unique_id
    from history_record hr
   where hr.unique_id is null
)
update hr
   set hr.unique_id = cte.gened_unique_id
  from history_record hr
       join update_id_cte cte
         on hr.key_sk = cte.key_sk

可能有比使用 CTE 更简单的方法来执行此操作。如何为每个 distinct生成和更新history_record表?uniqueidentifierkey_sk

标签: sqlsql-servertsqlsql-updatecommon-table-expression

解决方案


而不是select distinct,您可以使用group by

with update_id_cte as (
       select hr.key_sk, NEWID() as gened_unique_id
       from history_record hr
       where hr.unique_id is null
       group by hr.key_sk
      )
update hr
   set hr.unique_id = cte.gened_unique_id
   from history_record hr join
        update_id_cte cte
        on hr.key_sk = cte.key_sk;

如果某些key_sk值可能同时具有键NULL和非NULL键并且您想保留现有值,则可以调整逻辑:

with update_id_cte as (
       select hr.key_sk, coalesce(max(hr.unique_id), NEWID()) as gened_unique_id
       from history_record hr
       group by hr.key_sk
      )
update hr
   set hr.unique_id = cte.gened_unique_id
   from history_record hr join
        update_id_cte cte
        on hr.key_sk = cte.key_sk
   where hr.unique_id is null;

推荐阅读