在存储过程中创建具有角色的用户

时间:2019-03-25 16:07:28

标签: sql sql-server

我想创建在存储过程中具有角色的用户。我尝试了普通查询,但由于GO的原因而无法正常工作,然后我尝试将其放入存储过程中,但由于create PROCEDURE dbo.CreateUser AS BEGIN /*** Creating User ***/ DECLARE @SQL NVARCHAR(MAX) SET @SQL = ' CREATE USER [PRODUCTION\user1] FOR LOGIN [PRODUCTION\user1] WITH DEFAULT_SCHEMA=[dbo] GO sp_addrolemember @rolename = ''db_owner'', @membername = ''PRODUCTION\user1'' GO CREATE USER [PRODUCTION\user2] FOR LOGIN [PRODUCTION\user2] WITH DEFAULT_SCHEMA=[dbo] GO sp_addrolemember @rolename = ''db_owner'', @membername = ''PRODUCTION\user2'' GO' /*** Creating User ***/ EXEC(@SQL) END 的缘故,该查询也没有生效。我试图在动态查询中放入换行符,但也不起作用。有人可以帮忙吗?

resultlist = [[3, 2, 4, 4], [1, 6, 7, -6], [5, 4, 3, 2]]
max(resultlist)  # yields [5, 4, 3, 2] because 5 is the max in: 3, 1, 5
np.max(resultlist)  # yields 7 because it's the absolute max

1 个答案:

答案 0 :(得分:1)

我个人会这样做:

CREATE PROCEDURE dbo.CreateUser
AS
BEGIN
/*** Creating User ***/

    DECLARE @SQL  NVARCHAR(MAX)

    SET @SQL = N'CREATE USER [PRODUCTION\user1] FOR LOGIN [PRODUCTION\user1] WITH DEFAULT_SCHEMA=[dbo];' + NCHAR(13) + NCHAR(10) +
               N'CREATE USER [PRODUCTION\user2] FOR LOGIN [PRODUCTION\user2] WITH DEFAULT_SCHEMA=[dbo];';
    --PRINT @SQL; --Your debugging best friend
    EXEC sp_executesql @SQL;

    SET @SQL = N'ALTER ROLE db_owner ADD MEMBER [PRODUCTION\user1];' + NCHAR(13) + NCHAR(10) +
               N'ALTER ROLE db_owner ADD MEMBER [PRODUCTION\user2];';
    --PRINT @SQL; --Your debugging best friend
    EXEC sp_executesql @SQL;

END

此方法不推荐使用sp_addrolemember过程。它还将创建和成员资格分为两个独立的批次,以确保确实创建了用户。