Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use database inside a stored procedure

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 [userLogin]  USE [database2]  CREATE USER [userLogin] FOR LOGIN [userLogin] 

Since the CREATE USER statement does his job in the current database I need to use the USE statement to change between databases, but it can't be used inside stored procedures.

How can I do this?

like image 786
Lamelas84 Avatar asked Nov 17 '11 11:11

Lamelas84


People also ask

Can a stored procedure call another database?

The project uses multiple database so a stored procedure may call tables in another database.

How can use database name in stored procedure in SQL Server?

You can use Dynamic SQL to change the Database Name and run query against that database as shown in below example. You can create this stored procedure in any of the Database you want. Once you run the Stored Procedure, It is going to get the user databases list and then use Cursor to loop through.

Can we insert data in stored procedure?

Summary. A single stored procedure can be used to select, add, update, and delete data from a database table.

Can we use function inside stored procedure?

According to Microsoft standard, stored procedures cannot be executed inside the function, but technically it is possible with some tweaks.


1 Answers

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 
like image 174
gbn Avatar answered Sep 23 '22 09:09

gbn