Application.AddRoleMemberIfNonexistent
Documentation | WideWorldImporters |
Schema | Application |
Name | AddRoleMemberIfNonexistent |
Input/Output
Mode | Name | Data type | Description | |
---|---|---|---|---|
1 | IN | RoleName | nvarchar(128) | |
2 | IN | UserName | nvarchar(128) |
Script
CREATE PROCEDURE [Application].AddRoleMemberIfNonexistent @RoleName sysname, @UserName sysname WITH EXECUTE AS OWNER AS BEGIN SET NOCOUNT ON; SET XACT_ABORT ON; IF NOT EXISTS (SELECT 1 FROM sys.database_role_members AS drm INNER JOIN sys.database_principals AS dpr ON drm.role_principal_id = dpr.principal_id AND dpr.type = N'R' INNER JOIN sys.database_principals AS dpu ON drm.member_principal_id = dpu.principal_id AND dpu.type = N'S' WHERE dpr.name = @RoleName AND dpu.name = @UserName) BEGIN BEGIN TRY DECLARE @SQL nvarchar(max) = N'ALTER ROLE ' + QUOTENAME(@RoleName) + N' ADD MEMBER ' + QUOTENAME(@UserName) + N';' EXECUTE (@SQL); PRINT N'User ' + @UserName + N' added to role ' + @RoleName; END TRY BEGIN CATCH PRINT N'Unable to add user ' + @UserName + N' to role ' + @RoleName; THROW; END CATCH; END; END; |
Exported: 2019-02-04 23:04, Last imported: 2018-08-10 09:51