Microsoft SQL:多个数据库的抽象脚本
我需要将图像目录记录从一台服务器复制到另一台数据库名称以 p_
开头的服务器,我可以像这样对其进行硬编码(众多语句之一):
delete
from p_PhotoDB.dbo.item_keyword
where not exists (
select null as nothing
from OtherServer.p_PhotoDB.dbo.item_keyword new
where p_PhotoDB.dbo.item_keyword.item_id = new.item_id and
p_PhotoDB.dbo.item_keyword.keyword_id = new.keyword_id
)
我知道我可以将整个内容放入一个字符串变量和 exec (@variable)
,但这会每次针对每个目录的每个语句进行编译...
有没有办法更改每个找到的 p_PhotoDB
引用以 p_
开头的数据库而不使用某种形式的 exec (@variable)
?
I need to replicate image catalog records from one server to another who's database names start with p_
I can hard code it like so (one out of many statements):
delete
from p_PhotoDB.dbo.item_keyword
where not exists (
select null as nothing
from OtherServer.p_PhotoDB.dbo.item_keyword new
where p_PhotoDB.dbo.item_keyword.item_id = new.item_id and
p_PhotoDB.dbo.item_keyword.keyword_id = new.keyword_id
)
I know I could put the entire thing in a string variable and exec (@variable)
, but this would compile each time for each statement for each catalog ...
Is there a way to change the p_PhotoDB
reference for each found database starting with p_
without using some form of exec (@variable)
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Zim 博士,
据我所知,这无法在数据库级别完成。
当然,有一些工具可以帮助您做到这一点,例如 Redgate Compare,或内置于各种版本的 Visual Studio 中。
如果您需要一种在定期运行的脚本中自动执行此操作的方法,您也许可以对表使用 SYNONYMS,但肯定需要一些前期工作,并且在许多情况下它绝对没有用。请参阅:http://msdn.microsoft.com/en-us/library/ms177544 .aspx
我希望这有帮助。
Dr Zim.,
To the best of my knowledge, that can't be done at the database level.
There are, of course, tools that can help you do this such as Redgate Compare, or built into various versions of Visual Studio.
If you need a way to automate this in a periodically running script, you might be able to use SYNONYMS for tables, but there is definitely some up front work required there, and it is definitely not useful in a number of situations. SEE: http://msdn.microsoft.com/en-us/library/ms177544.aspx
I hope this helps.
不要使用
exec(@variable)
,而是使用exec sp_ExecuteSQL
。它创建一个执行计划,而不是为每次执行创建一个新计划。请参阅 MSDN 的使用 sp_ExecuteSQL 文章。然后,您可以使用动态 SQL 更改数据库名称或使用循环来循环访问一组数据库。在半伪代码中:Instead of using
exec(@variable)
, useexec sp_ExecuteSQL
. It creates one execution plan as opposed to a new one for each execution. See MSDN's Using sp_ExecuteSQL article. You can then use dynamic SQL to change the dbname or use a loop to loop through a set of databases. In semi-pseudocode: