我在脚本文件中有以下代码:
sqlcmd -E -I -S MyServerName -d MyDb1 -i D:\Updates\script.sql -o D:\Result\MyDb1.txt
sqlcmd -E -I -S MyServerName -d MyDb2 -i D:\Updates\script.sql -o D:\Result\MyDb2.txt
sqlcmd -E -I -S MyServerName -d MyDb3 -i D:\Updates\script.sql -o D:\Result\MyDb3.txt
我还有更多的数据库要更新,但这只是一个例子,我有一个.bat文件,它读取每个句子并在每个数据库中执行script.sql,这可以正常工作,但是现在我正在使用SQL Data工具生成脚本所以visual studio为我生成了脚本,问题是它创建了变量并在变量中添加了数据库名称,我需要能够每次访问每个数据库时都更新该变量,并以sql模式运行脚本。 / p>
这是MyDb1的script.sql示例:
/*
Deployment script for MyDb1
This code was generated by a tool.
Changes to this file may cause incorrect behavior and will be lost if
the code is regenerated.
*/
GO
SET ANSI_NULLS, ANSI_PADDING, ANSI_WARNINGS, ARITHABORT, CONCAT_NULL_YIELDS_NULL, QUOTED_IDENTIFIER ON;
SET NUMERIC_ROUNDABORT OFF;
GO
:setvar DictionaryData "DictionaryData"
:setvar DatabaseName "MyDb1"
:setvar DefaultFilePrefix "MyDb1"
GO
:on error exit
GO
/*
Detect SQLCMD mode and disable script execution if SQLCMD mode is not supported.
To re-enable the script after enabling SQLCMD mode, execute the following:
SET NOEXEC OFF;
*/
:setvar __IsSqlCmdEnabled "True"
GO
IF N'$(__IsSqlCmdEnabled)' NOT LIKE N'True'
BEGIN
PRINT N'SQLCMD mode must be enabled to successfully execute this script.';
SET NOEXEC ON;
END
GO
USE [$(DatabaseName)];
GO
PRINT N'Altering [cimpl].[LanguageView]...';
GO
ALTER VIEW [dbo].[LanguageView]
AS
SELECT l.LanguageLabelId, ll.[Name]
FROM [$(DictionaryData)].[dict].[Language] l
INNER JOIN [$(DictionaryData)].[dict].[LanguageType] lt
ON l.[LanguageTypeId] = lt.[LanguageTypeId]
INNER JOIN [$(DictionaryData)].[dict].[LanguageLabel] ll
ON ll.[LanguageLabelId] = l.[LanguageLabelId]
LEFT JOIN [cimpl].[LanguageConfiguration] lc
ON (lc.[LanguageLabelId] = l.[LanguageLabelId])
AND lc.[LanguageTypeId] = lt.[LanguageTypeId]
AND lc.[Active] = 1
WHERE l.Active = 1
GO
脚本更长,但是作为示例,您可以看到代码是自动生成的,但是对于MyDb1,现在我需要在MyDb2和MyDb3上运行它
如何动态替换句子:
:setvar DatabaseName "MyDb1"
作者:
:setvar DatabaseName "MyDb2" and :setvar DatabaseName "MyDb3"
当时正在运行sqlcmd?