开发者

Dynamically Specify Linked Server and DB Names in Stored Procedure

I have a query in a stored procedure that needs to be executed on different servers and databases according to some parameters.

How can I do this without using neither exec, nor sp_executesql?

I'm using SQL Server 2008.

Thank you.

UPDATE

I've found some links

http://www.eggheadcafe.com/software/aspnet/29397800/dynamically-speci开发者_JAVA百科fy-serve.aspx

http://www.sommarskog.se/dynamic_sql.html

Is using SYNONYM possible solution? If yes, than how?

UPDATE 2

I forgot to mention that all this servers are linked to the server where stored procedure is stored.

UPDATE 3

OPENROWSET or OPENDATASOURCE are not accessible either. I need a solution without building query string concating server name, schema name, db name.

It surely can be done by using if or case in stored procedure, but if we have 37 variations, then it's not a good solution.

Any other suggestions?


Nobody wants to answer, so I'll do it myself, just to have accepted answer.

There's isn't any way to do this. You need to use one of specified suggestions, anyway the query must be generating by concatenating.


Does OPENROWSET or OPENDATASOURCE help?

EDIT: If it works, you can change the database at runtime & execute the query using the present connection. I cannot see any other way of executing query the way you want.

What is wrong with running query using string i.e dynamic query?


/* DO THIS FOR EACH TABLE IN THE PROCEDURE*/ 

--BEGIN TABLE_1  
DECLARE @LINKEDSERVER AS VARCHAR(50) 
 SET @LINKEDSERVER = DBO.FN_RETURN_SERVER('SBROUBLES')

DROP SYNONYM MYLINKEDSERVER
EXEC (' CREATE SYNONYM MYLINKEDSERVER FOR ' + @LINKEDSERVER + 'ANYDB.DBO.ANYTABLE')

--- END TABLE_1

-- UTILIZATION
SELECT COUNT(*) FROM MYLINKEDSERVER


--AND FN_RETURN_SERVER COULD BE ANY SELECT CASE ON SQL AS WELL
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜