0

I need to check if the user has access based on their roles. (ASP.NET and SQL Server)

SELECT rf.ReadAccess
FROM aspnet_Users as u INNER JOIN aspnet_Roles as r ON r.UserID=u.UserID
INNER JOIN RolesByForm as rf ON rf.RoleID=r.RoleID
WHERE u.UserID=@UserID

So this gets me close, but this is what I really want. I want forms visible by default, so if there is no record in RolesByForm, it should be "True". But if there is a record it should return based on the ReadAccess field.

How do I get the query to return a Boolean?

3
  • it would be helpful to post your ASP.NET code that uses this query as well.
    – jwl
    Nov 18, 2011 at 21:21
  • If there is no record, there is no record. You shouldn't rely on the SQL query to make your forms visible by default, but use code.
    – Otiel
    Nov 18, 2011 at 21:23
  • There is no boolean in TSQL. However you can return a BIT of 0 or 1 which you can cast in your application with a ternary function.
    – SQLMason
    Nov 18, 2011 at 21:24

5 Answers 5

1

Try

SELECT case count(rf.ReadAccess) when 0 then 'True' else 'False' end ReadAccess 
FROM aspnet_Users as u INNER JOIN aspnet_Roles as r ON r.UserID=u.UserID
INNER JOIN RolesByForm as rf ON rf.RoleID=r.RoleID
WHERE u.UserID=@UserID
0
SELECT ReadAccess=CASE rf.ReadAccess WHEN 1 THEN 'True' ELSE 'False' END
FROM aspnet_Users as u INNER JOIN aspnet_Roles as r ON r.UserID=u.UserID
INNER JOIN RolesByForm as rf ON rf.RoleID=r.RoleID
WHERE u.UserID=@UserID

And in your .net code write something like:

bool result;
bool myBoolean=Boolean.TryParse(dataset["ReadAccess"], out result);
0

In .NET the Sql Server field BIT is true or false, so:

CAST ( rf.ReadAccess as BIT)

Or if ReadAccess is a varchar:

CASE ReadAccess
   WHEN 'Something' THEN CAST(1 as bit)
   ELSE CAST (0 as bit)
END
0

Assuming rf.ReadAccess is a bit field (1 or 0) then you want an outer join to capture the non existence of a rolesbyform record.

Something like this perhaps?

SELECT distinct isnull(rf.ReadAccess, 1) as ReadAccess
FROM aspnet_Users as u INNER JOIN aspnet_Roles as r ON r.UserID=u.UserID
LEFT OUTER JOIN RolesByForm as rf ON rf.RoleID=r.RoleID
WHERE u.UserID=@UserID
0

You can return 0 (false) and 1 (true). Try this example:

CREATE PROCEDURE CheckReadAccess 
@UserID INT
AS

BEGIN
DECLARE @rdAxs VARCHAR(255)

    SELECT @rdAxs = rf.ReadAccess
    FROM aspnet_Users as u INNER JOIN aspnet_Roles as r ON r.UserID=u.UserID
    INNER JOIN RolesByForm as rf ON rf.RoleID=r.RoleID
    WHERE u.UserID=@UserID

    IF @rdAxs IS NULL
        RETURN 0
    ELSE
        RETURN 1

END

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.