创建动态数据 SQL

Create a Dynamic data SQL

我的 sql 服务器数据库中有两个 table

第一 table

SID--Role
1--A
2--B
3--C
4--D
5--E

第 2 table

RoleName--SID
Admin--1
Admin--4
QA--2

角色名 'Admin' 的输出应该是

SID--Role--Exists
1--A--true
2--B--false
3--C--false
4--D--true
5--E--false

你们能帮我一个select查询得到上面的输出吗

您似乎需要执行 joins(即 left join)并使用 case 表达式来检查角色(即 admin)是否存在。

select t.SID, t.Role,
       case when (t2.RoleName is not null and t2.RoleName = 'Admin') 
            then 'true' else 'false' end [Exists]
from table1 t
left join table2 t2 on t2.sid = t.sid

但是,您也可以使用 ANSI SQL 标准 COALESCE() 函数 if support

select t.SID, t.Role,
       case when coalesce(t2.RoleName, '') = 'Admin' 
            then 'true' else 'false' end [Exists]
from table1 t
left join table2 t2 on t2.sid = t.sid

利用 CASE 和 left Outer Join

SELECT A.SID, A.Role,CASE  RoleName WHEN 'Admin' THEN 'True' ELSE 'False' end AS 'Exists'
FROM  #TEMP_ROLE A LEFT OUTER JOIN #TEMP_ROLENAME ON a.SID = #TEMP_ROLENAME.SID

您也可以试试这个查询

DECLARE  @Role TABLE ([SID] INT,[Role] VARCHAR(1))
INSERT INTO @Role
SELECT 1,'A' UNION ALL SELECT 2,'B' UNION ALL SELECT 3,'C' UNION ALL SELECT 4,'D' UNION ALL SELECT 5,'E'

DECLARE @RoleDetails TABLE (SID INT,RoleName VARCHAR(100))
INSERT INTO @RoleDetails
SELECT 1,'ADMIN' UNION ALL SELECT 4, 'ADMIN' UNION ALL SELECT 2,'QA'

(SELECT B.[SID],A.[Role],'True' AS EXIST FROM @Role A 
INNER JOIN @RoleDetails B ON A.[SID] = B.[SID] AND B.RoleName = 'ADMIN')
UNION ALL
(SELECT A.[SID],A.[Role],'False' AS EXIST FROM @Role A 
LEFT JOIN @RoleDetails B ON A.[SID] = B.[SID] WHERE A.[SID] NOT IN 
(SELECT A.[SID] FROM @Role A INNER JOIN @RoleDetails B ON A.[SID] = B.[SID] AND B.RoleName = 'ADMIN')) 

谢谢