SQL Server 2016:如何为规范化表设置行级安全性(RLS)

时间:2017-06-10 12:26:30

标签: sql-server sql-server-2016 row-level-security

我有三个表MST_EMployeeMST_ProfitCenterMapping_Employee_ProfitCenter。我想在Mapping_Employee_ProfitCenter表上设置行级安全性。

我要完成的步骤:

步骤1:创建一个表值函数:

CREATE FUNCTION [RLS].[fn_CanSeeMapping] ( @UserName AS sysname )
RETURNS TABLE
WITH SCHEMABINDING 
AS
   RETURN
        (SELECT 1 AS 'CanSee' 
         WHERE @UserName IN (SELECT emp.ATTRFirstName  
                             FROM dbo.MAPPING_Employee_ProfitCenter map 
                             INNER JOIN dbo.MST_Employee emp ON map.FK_Employee_ID = emp.Id
                             WHERE emp.ATTRFirstName = USER_NAME())

步骤2:创建安全策略并在映射表上添加过滤器,并将用户名作为参数传递给映射表中存在的id。

CREATE SECURITY POLICY [dbo].[Security_Policy] 
ADD FILTER PREDICATE [RLS].[fn_CanSeeMapping]([FK_Employee_ID]) ON  [dbo].[MAPPING_Employee_ProfitCenter] 

ALTER SECURITY POLICY [dbo].[Security_Policy] WITH (STATE = ON)

现在当我执行下面的查询而不是为用户" User1"它是为所有用户提供的。

EXEC ('select * from MAPPING_Employee_ProfitCenter') as user='User1'

如果有人知道如何处理这种情况,请帮助我。

谢谢!

1 个答案:

答案 0 :(得分:0)

尝试以下,这应该是适当的语法:

EXECUTE AS USER = 'User1';  
select * from MAPPING_Employee_ProfitCenter;   
REVERT;