Use database inside a stored procedure

后端 未结 7 1414
故里飘歌
故里飘歌 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:07

    It should be noted that if you want to use single quotes within a EXEC command, you will need to double the amount of single quotes

    e.g.

    EXEC ('USE [database1]; select * from Authors where name = ''John'' ')
    

    In this example, John has 2 single quotes before and after it. You cannot use double quotes for this type of query.

    0 讨论(0)
  • 2020-12-10 11:14

    Dynamic SQL

    CREATE PROCEDURE spTestProc
    AS
    
    EXEC ('USE [database1]; CREATE USER [userLogin] FOR LOGIN [userLogin]')
    
    EXEC ('USE [database2]; CREATE USER [userLogin] FOR LOGIN [userLogin]')
    GO
    
    0 讨论(0)
  • 2020-12-10 11:19

    If you're writing dynamic SQL with EXEC sp_executesql ('query1') or EXEC ('query2') this will return correct db which you want. If you're writing static SQL or your query outside of dynamic SQL quotes or parantheses it will work on master (where you create stored procedure(default is master)).

    CREATE PROCEDURE master.dbo.mysp1
    AS
    
        EXEC ('USE model; SELECT DB_NAME()') -- or sp_executesql N'USE model; SELECT DB_NAME()' 
        --this returns 'model'
    
    GO
    
    
    CREATE PROCEDURE master.dbo.mysp2
    AS
    
        EXEC ('USE model;') -- or sp_executesql N'USE model;'
        SELECT DB_NAME() 
        -- this returns 'master'
    
    GO
    
    0 讨论(0)
  • 2020-12-10 11:24
    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
    

    now it is worked.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-10 11:30

    I did it like below:

    Alter Procedure testProc
    @dbName varchar(50)
    As
    declare @var varchar(100)
    set @var = 'Exec(''create table tableName(name varchar(50))'')'    
    Exec('Use '+ @dbName + ';' + @var)
    Exec testProc 'test_db'
    
    0 讨论(0)
提交回复
热议问题