Insert into SQL table 仅为没有条目的记录

Insert into SQL table only for records with no entry

我有两个 table:

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

对于用户拥有的每个角色,cSc_userRole 中都有一个条目。此 table 中 camosGUID 的 FK 是 UserGUID。还有一列RoleGUID。我只想考虑一个具有 RoleGUID = AD3BB.

的角色

现在我的目标是在 cSc_UserRole 中为每个没有 RoleGuid = AD3BB 角色条目的用户创建一条记录。另外我想用 camosGUID = -12032.

排除两个用户

这是我已经完成的。问题是如果用户已经拥有该角色,它也会在 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'))

下面的查询将 return 您正在寻找的用户。我会把它留在视图中。

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