Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set database name dynamically in SQL Server stored procedure?

Tags:

sql-server

How do I set the database name dynamically in a SQL Server stored procedure?

like image 363
Srikar Doddi Avatar asked Jan 15 '10 17:01

Srikar Doddi


3 Answers

Sometimes, the use of SYNONYMs is a good strategy:

CREATE SYNONYM [schema.]name FOR [[[linkedserver.]database.]schema.]name

Then, refer to the object by its synonym in your stored procedure.

Altering where the synonym points IS a matter of dynamic SQL, but then your main stored procedures can be totally dynamic SQL-free. Create a table to manage all the objects you need to reference, and a stored procedure that switches all the desired synonyms to the right context.

This functionality is only available in SQL Server 2005 and up.

This method will NOT be suitable for frequent switching or for situations where different connections need to use different databases. I use it for a database that occasionally moves around between servers (it can run in the prod database or on the replication database and they have different names). After restoring the database to its new home, I run my switcheroo SP on it and everything is working in about 8 seconds.

like image 130
ErikE Avatar answered Nov 11 '22 20:11

ErikE


Stored Procedures are database specific. If you want to access data from another database dynamically, you are going to have to create dynamic SQL and execute it.

Declare @strSQL VarChar (MAX)
Declare @DatabaseNameParameter VarChar (100) = 'MyOtherDB'

SET @strSQL = 'SELECT * FROM ' + @DatabaseNameParameter + '.Schema.TableName'

You can use if clauses to set the @DatabaseNameParameter to the DB of your liking.

Execute the statement to get your results.

like image 11
Raj More Avatar answered Nov 11 '22 22:11

Raj More


This is not dynamic SQL and works for stored procs

Declare @ThreePartName varchar (1000)
Declare @DatabaseNameParameter varchar (100)

SET @DatabaseNameParameter = 'MyOtherDB'

SET @ThreePartName = @DatabaseNameParameter + '.Schema.MyOtherSP'

EXEC @ThreePartName @p1, @p2...   --Look! No brackets
like image 4
gbn Avatar answered Nov 11 '22 22:11

gbn