问题
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