Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating stored procedure in another database

Tags:

People also ask

Can a stored procedure access another database?

The stored procedure can't move to a new database if it's coded.

How can use two database in stored procedure?

If we're talking about two databases on the same server: yes, a stored procedure can access another database. You have to make sure that the user under whose privileges the procedure is being run has the necessary privileges on each database.

How do I copy a SQL procedure from one database to another?

Launch MS SQL Server Management Studio in your system and go to the Object Explorer. Step 2. Right-click on the database from which you want to move data and then click on Tasks>>Generate Scripts… A Generate and Publish Scripts Wizard will appear on the screen, click on the Next button to proceed.


Any idea if it's possible to create a procedure in another database using T-SQL alone, where the name of the database is not known up front and has to be read from a table? Kind of like this example:

Use [MasterDatabase]
Declare @FirstDatabase nvarchar(100)
Select Top 1 @FirstDatabase=[ChildDatabase] From [ChildDatabases]
Declare @SQL nvarchar(4000)
Declare @CRLF nvarchar(10) Set @CRLF=nchar(13)+nchar(10)
Set @SQL =
    'Use [+'@Firstdatabase+']'+@CRLF+
    'Go'+@CRLF+
    'Create Proc [Test] As Select 123'
Exec (@SQL)

See what I'm trying to do? This example fails because Go is actually not a T-SQL command but it something recognised by the query analyser/SQL management studio and produces an error. Remove the Go and it also fails because Create Proc must be the first line of the script. Arrgg!!

The syntax of T-SQL doesn't allow you do things like this:

Create [OtherDatabase].[dbo].[Test]

Which is a shame as it would work a treat! You can do that with Select statements, shame it's inconsistent:

Select * From [OtherDatabase]..[TheTable]

Cheers, Rob.