Use database inside a stored procedure

后端 未结 7 1415
故里飘歌
故里飘歌 2020-12-10 10:30

I need to make a stored procedure which creates a user in more than one database. Something like this:

USE [database1]

CREATE USER [userLogin] FOR LOGIN [us         


        
相关标签:
7条回答
  • 2020-12-10 11:31

    SQL Server gives us a system stored procedure to do this. My understanding is that the recommended method would be to use sys.sp_grantdbaccess:

    CREATE PROCEDURE usp_CreateTwoUSers
    
    AS
    BEGIN
    
        -- Create a user for a login in the current DB:
        Exec sp_grantdbaccess [userLogin], [name_in_db];
    
        -- Create a user for a login in an external DB:
        Exec ExternalDatabaseName.sys.sp_grantdbaccess [userLogin], [name_in_db];
    
    END
    
    0 讨论(0)
提交回复
热议问题