SQL Server Query to set variables based on matching id in a row in the resultset

dbf7pr2w  于 2023-05-28  发布在  其他
关注(0)|答案(2)|浏览(129)

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
mrzz3bfm

mrzz3bfm1#

If you want to set your variables IsAdmin , IsSuperUser , and IsUser in one query, you can use the conditional aggregation like the following:

DECLARE @IsAdmin BIT, @IsSuperUser BIT, @IsUser BIT

SELECT
    @IsAdmin = MAX(CASE WHEN RoleId = 1 THEN 1 ELSE 0 END),
    @IsSuperUser = MAX(CASE WHEN RoleId = 3 THEN 1 ELSE 0 END),
    @IsUser = MAX(CASE WHEN RoleId = 5 THEN 1 ELSE 0 END)
FROM
    AspNetUserRoles
WHERE
    UserId = @CallerUserId

In this query, the MAX function is used with conditional expression ( CASE WHEN ) inside. Each conditional expression checks the RoleId and assigns either 1 or 0 based on the condition. The result of each one is then the aggregation using MAX to obtain a single value for each variable.

Note that the query assumes that the AspNetUserRoles table contains the columns RoleId and UserId , which are used for filtering the data. Adjust the table and column names as per your schema.

x6yk4ghg

x6yk4ghg2#

With no sample data I can't test this of course but you can aggregate, something like

select 
    @IsAdmin = IsNull(max(case when RoleId = 1 then 1 end),0)
    @IsSuperUser = IsNull(max(case when RoleId = 3 then 1 end),0)
    @IsUser = IsNull(max(case when RoleId = 5 then 1 end),0)
from #CallerRoles;

相关问题