This script will return true or false after testing that a userid is in a given role or is superuser
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[_LIS_HasRole]
@UserID int
,@RoleName nvarchar(150)
AS
DECLARE @CheckUserID int
DECLARE @HitCount int = 0
SET @CheckUserID = @UserID
IF @CheckUserID <> 0
BEGIN
--if user is superuser
SET @HitCount = (SELECT IsSuperUser FROM Users WHERE UserID = @CheckUserID)
-- if user is administrator
SET @HitCount = @HitCount + (
SELECT COUNT(*)
FROM UserRoles INNER JOIN
Roles ON UserRoles.RoleID = Roles.RoleID INNER JOIN
Users ON UserRoles.UserID = Users.UserID
WHERE Roles.Rolename = 'Administrators' AND Users.UserID = @CheckUserID)
--is user in the queried role
SET @HitCount = @HitCount + (
SELECT COUNT(*)
FROM UserRoles INNER JOIN
Roles ON UserRoles.RoleID = Roles.RoleID INNER JOIN
Users ON UserRoles.UserID = Users.UserID
WHERE Roles.Rolename = @RoleName AND Users.UserID = @CheckUserID)
--return the answer
SELECT CAST(CASE WHEN @HitCount > 0 THEN 'True' ELSE 'False' END AS nvarchar(10)) AS HasRole
END
ELSE
SELECT 'False' AS HasRole
____________________________
Or if you need to make this determination without a stored procedure
Two other ways to do this with SQL are in the article read more