Given a resultset with one row per role, how do I set my three variables like IsAdmin, IsSuperUser, IsUser.
I tried this, but it's super ugly. I want to accomplish the same with just one query. I know how to combine them into one query with three subqueries but I'd like to get away with only one query if it's possible.
declare @IsAdmin bit, @IsSuperUser bit, @IsUser bit
select RoleId into #CallerRoles from AspNetUserRoles aur where aur.UserId = @CallerUserId
set @IsAdmin = case when exists (select * from #CallerRoles where RoleId = 1) then 1 else 0 end
set @IsSuperUser = case when exists (select * from #CallerRoles where RoleId = 3) then 1 else 0 end
set @IsUser = case when exists (select * from #CallerRoles where RoleId = 5) then 1 else 0 end
2条答案
按热度按时间mrzz3bfm1#
If you want to set your variables
IsAdmin
,IsSuperUser
, andIsUser
in one query, you can use the conditional aggregation like the following:In this query, the
MAX
function is used with conditional expression (CASE WHEN
) inside. Each conditional expression checks theRoleId
and assigns either 1 or 0 based on the condition. The result of each one is then the aggregation usingMAX
to obtain a single value for each variable.Note that the query assumes that the
AspNetUserRoles
table contains the columnsRoleId
andUserId
, which are used for filtering the data. Adjust the table and column names as per your schema.x6yk4ghg2#
With no sample data I can't test this of course but you can aggregate, something like