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 中将数据库名称设置为变量
基础教程推荐
- 无法解决整理冲突 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 在 SQL 中连接多个表 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
