如何将 CTE 的结果插入 table 中,其中某些列具有常量值

How to insert the result of CTE in a table with constant values for some columns

我想使用带有一些常量值的 CTE 结果插入 table

;With CTE as
(
    select distinct 
        client_user_id 
    from 
        profiles.client_users_data 
    where 
        signal_name = 'Level' 
        and signal_value in (1, 2, 3, 4, 5) 
        and client_user_id not in (select distinct client_user_id 
                                   from [profiles].[client_user_mapping])
)
insert into [profiles].[client_user_mapping]
(786 as client_id, newid() as da_user_id, client_user_id from CTE);

怎么做?

使用insert . . . select:

With CTE as (
      select distinct client_user_id 
      from profiles.client_users_data 
      where signal_name = 'Level' and
            signal_value in (1, 2, 3, 4, 5) and
            client_user_id not in (select distinct client_user_id from [profiles].[client_user_mapping])
      )
insert into [profiles].[client_user_mapping] (client_id, da_user_id, client_user_id)
    select 786 as client_id, newid() as da_user_id, client_user_id
    from CTE;

请注意,我添加了一个列列表。这是进行插入时的最佳做法。

我强烈建议您对子查询使用 NOT EXISTS 而不是 NOT IN。如果任何返回值为 NULLNOT IN 不会执行您期望的操作。所以:

With CTE as (
      select distinct ud.client_user_id 
      from profiles.client_users_data  ud
      where ud.signal_name = 'Level' and
            ud.signal_value in (1, 2, 3, 4, 5) and
            not exists (select distinct
                        from [profiles].[client_user_mapping] um
                        where um.client_user_id = ud.client_user_id
                       )
     )

此外,您可以为 da_user_id 设置一个默认值,这样您就不必明确地将其设置为 newid()

仅仅因为它是一个 CTE 并不会改变 INSERT 的语法。它仍然是 INSERT INTO...SELECT...FROM:

WITH CTE AS
    (SELECT DISTINCT
            client_user_id
     FROM profiles.client_users_data
     WHERE signal_name = 'Level'
       AND signal_value IN (1, 2, 3, 4, 5)
       AND client_user_id NOT IN (SELECT DISTINCT client_user_id FROM [profiles].[client_user_mapping]))
INSERT INTO [profiles].[client_user_mapping]
SELECT 786 AS client_id,
       NEWID() AS da_user_id,
       client_user_id
FROM CTE;

SQL 服务器希望所有值在 CTE 中的顺序正确。因此,要完成任务,正确的查询将是:

;With CTE as
(
select distinct 786 as client_id,client_user_id,newid() as da_user_id from 
profiles.client_users_data 
where signal_name='Level' And signal_value in (1,2,3,4,5) 
And client_user_id not in (select distinct client_user_id from [profiles]. 
[client_user_mapping])
)
insert into [profiles].[client_user_mapping]
select client_id,client_user_id,da_user_id from CTE;

CTE 声明看起来不错,您的 Insert 语句需要调整为如下所示:

INSERT INTO [profiles].[client_user_mapping](client_id, da_user_id, client_user_id)
SELECT 786, newid(), client_user_id 
FROM CTE