SQL Server 2012:选择的结果不等于字符串

时间:2017-12-08 15:29:21

标签: sql-server sql-server-2012

我有用户和角色。这是我的查询的一部分:

(select R.RoleName from [dbo].[aspnet_Roles] as R 
    join [dbo].[aspnet_UsersInRoles] as UR on R.RoleId = UR.RoleId
    join [dbo].[aspnet_Users] as U on UR.UserId = U.Userid
    where U.UserName = 'User1') <> 'Doctor' 

但是因为用户可以拥有多个角色(在这种情况下User1DoctorClient),我会收到此错误:

  

子查询返回的值超过1。当子查询遵循=,!=,&lt;,&lt; =,&gt;,&gt; =或子查询用作表达式时,不允许这样做。

我如何使其工作,以便查询将返回用户的角色,他们的角色都不是Doctor

2 个答案:

答案 0 :(得分:2)

尝试NOT EXISTS

WHERE NOT EXISTS (SELECT *
                  FROM [dbo].[aspnet_Roles] Rsq 
                       JOIN [dbo].[aspnet_UsersInRoles] URsq ON Rsq.RoleId = URsq.RoleId
                       JOIN [dbo].[aspnet_Users] Usq ON UR.UserId = Usq.Userid
                  WHERE Usq.UserName = [Outside Query User ID Field]
                    AND Rsq.RoleName = 'Doctor')

答案 1 :(得分:1)

你做错了。试试这个

 ; WITH CTE AS 
(
    select DISTINCT U.UserName, R.RoleName from [dbo].[aspnet_Roles] as R 
    join [dbo].[aspnet_UsersInRoles] as UR on R.RoleId = UR.RoleId
    join [dbo].[aspnet_Users] as U on UR.UserId = U.Userid
)
SELECT * FROM CTE 
WHERE NOT EXISTS (SELECT 1 FROM CTE CIN WHERE CIN.UserName = CTE.UserName AND CIN.RoleName = 'Doctor')