Skip to content

Instantly share code, notes, and snippets.

@bitsprint
Created May 6, 2021 14:10
Show Gist options
  • Save bitsprint/e27b8d686e370922221873468b15cafd to your computer and use it in GitHub Desktop.
Save bitsprint/e27b8d686e370922221873468b15cafd to your computer and use it in GitHub Desktop.
SQL Row level security
-- DROP FUNCTION [dbo].[fn_tenantSecurityPredicate]
CREATE FUNCTION [dbo].[fn_tenantSecurityPredicate](@tenantId UNIQUEIDENTIFIER)
RETURNS TABLE
WITH SCHEMABINDING
AS
RETURN SELECT 1 AS [predicateResult]
FROM [dbo].[Users]
WHERE [Username] = CURRENT_USER
AND ([TenantId] IS NULL OR ([TenantId] IS NOT NULL AND @tenantId = [TenantId]));
GO
-- DROP SECURITY POLICY [dbo].[tenantSecurityPolicy]
CREATE SECURITY POLICY [dbo].[tenantSecurityPolicy]
ADD FILTER PREDICATE [dbo].[fn_tenantSecurityPredicate](TenantId) ON [dbo].[Customer],
ADD FILTER PREDICATE [dbo].[fn_tenantSecurityPredicate](TenantId) ON [dbo].[Orders]
WITH (STATE = ON);
GO
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment