Setting database name as a variable in SQL(在 SQL 中将数据库名称设置为变量)
问题描述
目前,我正在根据一些业务规则在一个数据库到另一个数据库之间进行一些数据迁移.
currently, I'm doing a bit of a data migration between one db to another based on some business rules.
我有一个巨大的脚本,我正在编写它,我在其中多次引用了两个数据库.问题是这种数据迁移目前正在开发中,在某些时候,我想在生产环境中使用两个不同的数据库进行迁移.
I have this huge script that I'm writing where I'm referencing both databases a lot of times. The problem is that this data migration is currently in development, at some point I am going to want to have to do it in production with two different databases.
而不是像这样直接引用数据库名称
Instead of referencing the database name directly like so
Insert Into Database2.dbo.Table1
Select * from Database1.dbo.Table1
我想以某种方式在脚本开始时引用数据库.这样我就可以在更改数据库时只更改一个变量.
I would like to somehow just reference the database at the start of the script. So that I can just change the one variable when I change databases.
这可能吗?
推荐答案
使用 SQLCMD变量:
:setvar dbfrom database1
:setvar dbto database2
Insert into [$(dbto)].dbo.Table1
select * from [$(dbfrom)].dbo.Table2;
此语法适用于 sqlcmd.exe(来自脚本)以及 Management Studio,请参阅 使用查询编辑器编辑 SQLCMD 脚本.脚本还允许您从命令行设置变量:
This syntax works in sqlcmd.exe (from scripts), as well as in Management Studio, see Editing SQLCMD Scripts with Query Editor. Scripting also allows you to set the variables from the command line:
sqlcmd /E /S server /i script.sql /v dbfrom=database1 /v dbto=database2
我还有一个库,允许您使用来自应用程序的 sqlcmd 变量和脚本作为 Google 代码的来源.
I also have a library that allows you to use sqlcmd variables and scripts from applications available as source on Google Code.
这篇关于在 SQL 中将数据库名称设置为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 SQL 中将数据库名称设置为变量


- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 更改自动增量起始编号? 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- SQL 临时表问题 2022-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01