UserSN
UserSN

Reputation: 1013

SQL Server Select statement with count

I'm writing a query to determine if a user is an administrator on my website or not.

I can't quite figure out how to display "True" or "False" after my initial select.

select count(*) as IsAdmin 
from UserRoles 
where UserID = '1' and RoleID = 1

IF count is != 0 => True
ELSE False

My IF is also not working, probably because I'm writing something incorrectly. RoleID=1 means they are administrators.

Upvotes: 2

Views: 58

Answers (2)

Gordon Bell
Gordon Bell

Reputation: 13633

select (case when UserID = '1' and RoleID = 1 then 1 else 0 end) as IsAdmin
from UserRoles

Upvotes: 1

S3S
S3S

Reputation: 25112

Use exists in your IF and then proceed with your logic / what you want to return

IF(exists(select 1 as IsAdmin from UserRoles where UserID='1' and RoleID = 1))
   SELECT 'IS ADMIN'
ELSE
   SELECT 'IS NOT ADMIN'

If in another scenario you were trying to check for a certain number, you can use it as such:

IF(select count(*) as IsAdmin from UserRoles where UserID='1' and RoleID = 1) > 0
   SELECT 'IS ADMIN'
ELSE
   SELECT 'IS NOT ADMIN'

Upvotes: 3

Related Questions