SQL Insert Into w/Subquery - Checking If Not Exists

为君一笑 提交于 2019-12-13 01:29:09

问题


Assume two tables - UserRole (UserRoleID, UserID, RoleID) and UserPermission (UserPermissionID, UserID, PermissionID, RegionID).

I have the following INSERT w/subquery to create new rows in UserPermission for every UserID with a certain RoleID:

INSERT INTO UserPermission (UserPermissionID, UserID, PermissionID, RegionID)
SELECT NEWID(), UserID, @PermID, NULL
FROM UserRole WHERE RoleID = '<specific guid>'

How can I check to see whether the rows I'm inserting don't already exist in the database? I know how to check for an individual record (IF NOT EXISTS(blah blah)), but what would be the best way to check whether a combination of a particular UserID and PermissionID (always going to be @PermID - a particular GUID) exist in a row in the UserPermission table?


回答1:


Should be achievable like this:

INSERT INTO UserPermission (UserPermissionID, UserID, PermissionID, RegionID)
SELECT NEWID(), UserID, @PermID, NULL
FROM UserRole r
WHERE RoleID = '<specific guid>'
AND NOT EXISTS (SELECT * FROM UserPermission WHERE UserID = r.UserID AND @PERMID = PermissionID);


来源:https://stackoverflow.com/questions/23786101/sql-insert-into-w-subquery-checking-if-not-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!