从用户函数内部的另一个数据库动态访问表 [英] Dynamic access to tables from another database inside an user function

查看:53
本文介绍了从用户函数内部的另一个数据库动态访问表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在SQL Server中有一个用户定义的表函数,该函数可聚合来自多个表(包括另一个数据库的几个表)中的数据。这样做是对查询中的数据库名称进行硬编码,但是我们希望使数据库名称可配置(因为我们的数据库通常与其他应用程序的数据库共享服务器)。



我尝试使用存储在配置表中的数据库名称在函数内部构造动态查询字符串,但是:


  1. 当我尝试 exec(@sqlStatement)时,SQL Server说函数内部不允许执行字符串。

  2. 然后我尝试了 exec sp_executesql @sqlStatement 并创建了该函数,但是当您执行该函数时,SQL Server表示在函数内部只能运行扩展函数和过程。

所以问题是:是否可以创建一个函数或存储过程来访问另一个数据库中的表,而不必在数据库名称不同时重新创建该函数? p>

TIA。

解决方案

我真的建议您使用固定的数据库名称,这样可以避免使用动态sql的整个问题。您不能拿出唯一的数据库名称,例如:您的公司名称_XYZ 您的公司名称_ABC ?如果这不是您的选择,那么您将进行大量的动态SQL,则应阅读动态的诅咒和祝福Erland Sommarskog编写的SQL



您在问题中提到的所有限制都是SQL Server函数的限制。您可以毫无问题地在存储过程中生成和执行动态SQL。


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.

解决方案

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.

这篇关于从用户函数内部的另一个数据库动态访问表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆