sql-server - 仅针对没有条目的记录插入 SQL 表
问题描述
我有两张桌子:
cSc_user
: 这里存储了每个用户。PK是camosGUIDcSc_UserRole
:当一个用户有一个角色时,这个用户的一行存储在这里
对于用户拥有的每个角色,在 中都有一个条目cSc_userRole
。camosGUID
此表中的FK 为UserGUID
. 还有一个专栏RoleGUID
。我只想考虑一个具有RoleGUID = AD3BB
.
现在我的目标是cSc_UserRole
为每个没有角色条目的用户创建一个记录RoleGuid = AD3BB
。此外,我想用camosGUID = -1
and排除两个用户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'))
解决方案
下面的查询将返回您正在寻找的用户。我会把它放在一个视图中。
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
推荐阅读
- vba - 如何使用 For Next 循环更新 Table Access 2007 VBA 中的列
- node.js - 如何使用 mongoose nodejs 在 mongdb 中的 dd/mm/yy fromat 中保存日期
- python - 有没有办法禁用抓取图片链接时附带的 cookie?
- lean - 如何在精益中证明 (∀ x, px ∨ r) ↔ (∀ x, px) ∨ r?
- c++ - 使用模板函数作为模板参数的 C++ 链接器错误
- javascript - 在本机反应中从firebase firestore数据库中提取firestore图像 - RangeError:超过最大调用堆栈大小
- mysql - 将现有列生成的输出作为新列添加到表中
- python - 熊猫排序不止一列不起作用
- python - 将值列表添加到 PySpark 数据框中的每一行
- python - Flask - 打印到 HTML 而不是控制台