在 SQL Server 中,有什么方法可以让“使用数据库"命令接受一个变量 [英] In SQL server is there any way to get the 'use database' command to accept a variable

查看:46
本文介绍了在 SQL Server 中,有什么方法可以让“使用数据库"命令接受一个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个通用"脚本来操作多个数据库.'use databasename' 命令将分布在脚本主体中.我宁愿在脚本顶部显示数据库名称信息.理想情况下:

<预>声明@db varchar(100)设置@db = 'data_in'使用@db

这失败了.所以也许

<预>声明@db varchar(100)设置@db = 'data_in'exec ('使用'+@db)

这会执行,但可能仅在字符串中查询的上下文中更改数据库.
那么有没有其他方法可以不将整个脚本放入一个字符串中并以这种方式执行它,即.比疾病更糟糕的治疗方法?

解决方案

SQLCMD.

这使您能够以以下形式将变量放入脚本中:

USE $(db1_name)...一些代码...使用 $(db2_name)...一些代码...

并从环境变量、运行时提供的参数或硬编码值分配中插入变量值.

I would like to write a 'generic' script to operate on a number of databases. The 'use databasename' commands will be distributed in the body of the script. I would rather show the database name information at the top of the script. So ideally:

declare @db varchar(100)
set @db = 'data_in'
use @db

This fails. So perhaps

declare @db varchar(100)
set @db = 'data_in'
exec ('use '+@db)

This executes, but presumably changes the database only in the context of the query in the string.
So is there any other way without placing the whole script into a string and executing it that way ie. a cure worse than the disease?

解决方案

Check out Scripting Variables in SQLCMD.

This enables you to put variables into your scripts in the form:

USE $(db1_name)
...some code...

USE $(db2_name)
...some code...

And have the variable values interpolated from environment variables, parameters provided at runtime, or hard coded value assignments.

这篇关于在 SQL Server 中,有什么方法可以让“使用数据库"命令接受一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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