Showing posts with label specify. Show all posts
Showing posts with label specify. Show all posts

Monday, March 19, 2012

Dynamically specify server and database in Stored Procedure

I am writing Stored Procedures on our SQL 2005 server that will link with data from an external SQL 2000 server. I have the linked server set up properly, and I have the Stored Procedures working properly. My problem is that to get this to work I am hardcoding the server.database names. I need to know how to dynamically specify the server.database so that when I go live I don't have to recompile all of my stored procedures with the production server and database name. Does anyone have any idea how to do this?
EXAMPLE:
SELECT field1, field2 FROM mytable LEFT OUTER JOIN otherserver.otherdatabase.dbo.othertable

OBJECTIVE:

Replace 'otherserver.otherdatabase.dbo.othertable' with some other process (dbo.fnGetTable('dbo.othertable')?)

Thanks for any help

Hi,

that is not (yet) parameterizable. You would have to use dynamic sql here.

HTH, Jens K. Suessmeyer.

http://www.sqlserver2005.de

Friday, March 9, 2012

Dynamically Choose Database

I have to write a large data migration script to move data from one SQL Server database to another. Is there any way to dynamically specify the server and database name? I would like to do something like the following, (but this does not seem to work):

Delete From [@.ServerName].[@.ImportToDatabase].[MyTable]

Any help appreciatedno. you can't do that.

EXECUTE 'DELETE FROM [' + @.ServerName + '].[' + @.ImportToDatabase + '].[username].[MyTable]'|||For some reason this doesn't seem to work in my code. However using:

EXEC ('DELETE FROM [' + @.ServerName + '].[' + @.ImportToDatabase + '].[username].[MyTable]' )

Does work.

Thanks for your comments