首页 > 解决方案 > 仅针对没有条目的记录插入 SQL 表

问题描述

我有两张桌子:

  1. cSc_user: 这里存储了每个用户。PK是camosGUID
  2. cSc_UserRole:当一个用户有一个角色时,这个用户的一行存储在这里

对于用户拥有的每个角色,在 中都有一个条目cSc_userRolecamosGUID此表中的FK 为UserGUID. 还有一个专栏RoleGUID。我只想考虑一个具有RoleGUID = AD3BB.

现在我的目标是cSc_UserRole为每个没有角色条目的用户创建一个记录RoleGuid = AD3BB。此外,我想用camosGUID = -1and排除两个用户2032

这是我已经做过的。cSc_UserRole问题是如果用户已经拥有该角色,它也会创建一个条目。所以它在运行查询后被复制。

INSERT INTO [csc_userrole] ([RSRC], [Deleted], [DateNew], [DateChanged],
                            [UserNew], [UserChanged], [camosGUID],
                            [UserGUID], [RoleGUID])
    SELECT
        0, 0, GETDATE(), GETDATE(),
        2032, 2032, NEWID(),
        camosGUID, 'AD3BB'
    FROM 
        [cSc_User] 
    WHERE 
        csc_user.camosguid <> -1 
        AND csc_user.camosguid <> 2032 
        AND (csc_user.camosguid NOT IN (SELECT userguid
                                        FROM cSc_Userrole) OR 
             csc_user.camosguid IN (SELECT userguid
                                    FROM cSc_Userrole
                                    WHERE roleguid <> 'AD3BB' 
                                      AND roleguid <> 'E5DEE'))

标签: sql-serverinsertnotin

解决方案


下面的查询将返回您正在寻找的用户。我会把它放在一个视图中。

select * 
from cSc_user
where
   --users that don't have a role of AD3BB
   UserGUID not in (select UserGUID from cSc_user where RoleGUID = 'AD3BB')
   --the camosGUIDs you want to exclude
   and camosGUID  not in (-1,2032)

所以,从某种角度...

create view myUserList
as
select * 
from cSc_user
where
   --users that don't have a role of AD3BB
   UserGUID not in (select UserGUID from cSc_user where RoleGUID = 'AD3BB')
   --the camosGUIDs you want to exclude
   and camosGUID  not in (-1,2032)

然后从中查询...

select * from myUserList

推荐阅读