我正在尝试创建一个Row Level Security Function
,如果当前登录的用户是ReportUser
,则返回访问权限。
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[userIdPredicate](@siteId AS INT)
RETURNS TABLE
WITH SCHEMABINDING
AS
BEGIN
IF (SUSER_SNAME() = 'ReportUser')
BEGIN
RETURN SELECT 1 AS accessResult
END
RETURN SELECT 1 AS accessResult
FROM dbo.UserGroup
JOIN dbo.[Group] ON [Group].Id = UserGroup.GroupId
JOIN dbo.SiteGroup ON SiteGroup.GroupId = [Group].Id
JOIN dbo.Site ON Site.Id = SiteGroup.SiteId
WHERE ApplicationUserId = CAST(SESSION_CONTEXT(N'UserId') AS NVARCHAR(450))
AND dbo.SITE.Id = @siteId
END
目前谓词在没有IF statement
的情况下正常工作,但是当我包含IF语句时,我收到错误
Msg 102,Level 15,State 31,Procedure userIdPredicate,Line 21
'BEGIN'附近的语法不正确。
我正在尝试做什么,如果可以,有人可以提出解决方案吗?
答案 0 :(得分:0)
您可以使用OR模拟IF。您可以在每个特定的OR中放置不同的查询,从而模拟IF。这是访问过滤的示例:
CREATE FUNCTION [rls].[subcodeAccessPredicate](@SubcodeId int)
RETURNS TABLE
WITH SCHEMABINDING
AS
RETURN
(
SELECT 1 AS fn_securitypredicate_result FROM [dbo].[DataAccesses]
-- if the companyUser has direct subcode access
WHERE SubcodeId = @SubcodeId AND CompanyUserId = SESSION_CONTEXT(N'CompanyUserId')
-- if a group in thich the companyUser is has direct subcode access
OR SubcodeId = @SubcodeId AND UserGroupId IN (SELECT UserGroup_Id FROM CompanyUserUserGroups WHERE CompanyUser_Id = SESSION_CONTEXT(N'CompanyUserId'))
-- if wathever
OR EXISTS (SELECT Id FROM somewhere WHERE somewhere.Id = 1 OR 2)
-- else give every row because this is not filtered
OR SESSION_CONTEXT(N'filteredForUser') = 0
)
GO