Use database inside a stored procedure

后端 未结 7 1442
故里飘歌
故里飘歌 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-10 11:28

    Using sp_executesql seems to work, for more info see http://msdn.microsoft.com/en-us/library/ms175170.aspx

    I tested it using this and it worked fine:

    CREATE PROCEDURE spTestProc
    AS
    BEGIN
    
    EXECUTE sp_executesql N'USE DB1;'
    
    SELECT * FROM TABLE1
    EXECUTE sp_executesql N'USE DB2;'
    
    SELECT * FROM Table2
    
    END
    
    exec spTestProc
    

提交回复
热议问题