Dynamic access to tables from another database ins

2019-05-11 20:34发布

问题:

I have an user defined table function in SQL Server that aggregate data from several tables including a couple of tables of another database. That is done hardcoding the name of the database in the queries, but we want to make the database name configurable (because our databases usually share the server with the databases of other applications).

I tried to construct a dynamic query string inside the function using the database name that is stored in a configuration table, but:

  1. When I tried exec(@sqlStatement) SQL Server said that execute string is not allowed inside a function.
  2. Then I tried exec sp_executesql @sqlStatement and the function was created, but when you execute it SQL Server says that inside a function you can only run extended functions and procedures.

So the question is: is possible create a function or stored procedure that access a table in another database without having to recreate the function when the database name is different?

TIA.

回答1:

I would really recommend that you settle on fixed database names, so you can avoid this entire problem of using dynamic sql. Can't you come up with unique database names like: your_company_name_XYZ and your_company_name_ABC? if that is not an option you will be doing lots of dynamic SQL, you should read The Curse and Blessings of Dynamic SQL by Erland Sommarskog

All of the restrictions you mention in the question are a limit of SQL Server functions. You can generate and execute dynamic SQL within a stored procedure with no problems.