求SQL Server查询语句:根据指定角色名输出SID、角色及存在状态
Solution for Your SQL Server Query
Got it, let's tackle this. The goal is to pull every SID from your first table, their corresponding Role, and a flag showing if that SID is assigned to the 'Admin' RoleName in the second table. Here's how to make it work:
Assumptions
First, let's use meaningful names for your tables (replace these with your actual table names if they differ):
UserRoles: Your first table with columnsSIDandRole(holds data like 1--A, 2--B)RoleAssignments: Your second table with columnsRoleNameandSID(holds data like Admin--1, Admin--4)
The Query
SELECT ur.SID, ur.Role, CASE WHEN ra.SID IS NOT NULL THEN 'true' ELSE 'false' END AS [Exists] FROM UserRoles ur LEFT JOIN RoleAssignments ra ON ur.SID = ra.SID AND ra.RoleName = 'Admin' ORDER BY ur.SID;
Breakdown of How It Works
- LEFT JOIN: This keeps every row from
UserRoles(your first table), even if there's no matching 'Admin' entry inRoleAssignments. That’s how we ensure we get all 5 SIDs in the result. - Filter in the JOIN Clause: Adding
ra.RoleName = 'Admin'directly to theONclause means we only join rows where the role is Admin. If we put this in aWHEREclause instead, it would filter out rows with no Admin match—something we don’t want here. - CASE Statement: Checks if the joined
SIDfromRoleAssignmentsexists (isn’t NULL). If it does, returns 'true'; otherwise, 'false'—exactly the flag you need. - ORDER BY: Sorts the results by
SIDto match the output order you specified.
Example Output
Running this query will give you exactly the format you asked for:
SID | Role | Exists ----|------|------- 1 | A | true 2 | B | false 3 | C | false 4 | D | true 5 | E | false
内容的提问来源于stack exchange,提问作者user8624282
相关产品推荐
相关产品推荐

