Dynamic access to tables from another database inside an user function

流过昼夜 提交于 2020-01-02 07:26:31

问题


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.



来源:https://stackoverflow.com/questions/2461482/dynamic-access-to-tables-from-another-database-inside-an-user-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!