Hi @Lộc Nguyễn
When I log in with the admin account, I can only see its own row, and cannot see rows with role='members'
OR (@username = USER_NAME() AND @role = 'admins' AND (username = @username OR role = 'members'))
The logic of the filter condition is kind weird. How could the role be both 'admins' and 'members'?
You could convert the roles to role_levels (like 1,2,3) for better filtering. Try this:
CREATE FUNCTION Security.fn_securitypredicate3
(@username AS nvarchar(50), @role AS varchar(10))
RETURNS TABLE
WITH SCHEMABINDING
AS
BEGIN
DECLARE @Role_lvl INT
SET @Role_lvl = CASE @role WHEN 'members' THEN 1
WHEN 'admins' THEN 2
WHEN 'ceos' THEN 3 END
RETURN
(
SELECT 1 AS Result
FROM (SELECT *,CASE role WHEN 'members' THEN 1 WHEN 'admins' THEN 2 WHEN 'ceos' THEN 3 END AS Row_Level FROM dbo.user)T
WHERE @username = USER_NAME()
AND (T.username = @username OR Row_Level < @Role_lvl)
)
END
This query might not work because I do not know your tables like. Hope this point you in the right direction.
Best regards,
Cosmog Hong
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".