我认为你把 GO 放在了错误的地方。
我使用 sqlcmd 进行无人值守安装,并重现了该问题并了解您的意思。
这就是我调用脚本传递参数的方式:
sqlcmd -S . -E -b -v Database="Test" -i "C:\temp\CreateDatabase.sql"
这是 CreateDatabase.sql 脚本文件:
:On Error exit
--:Out null
--:SetVar SQLCMDERRORLEVEL 18
-- USE [master] GO -- with this line it fails, but its in the Master context already
DECLARE @Database varchar(64);
DECLARE @Error int;
DECLARE @Path varchar(256);
DECLARE @BackUpPath varchar(256);
SET @Database = '$(Database)';
SET @Path = '';
SET @BackUpPath = '';
IF @Path IS NULL OR RTrim(@Path) = ''
SET @Path = (SELECT SUBSTRING(physical_name, 1, CHARINDEX('master.mdf', LOWER(physical_name)) - 1)
FROM master.sys.master_files
WHERE database_id = 1 AND file_id = 1);
ELSE IF Right(@Path, 1) != ''
SET @Path = @Path + '';
IF EXISTS(SELECT [name] as [Database]
FROM master.sys.databases
WHERE [name] = @Database)
RAISERROR ('Database already exists.', 18, 10); -- :Exit(SELECT 10)
EXECUTE('CREATE DATABASE ' + @Database + ' ON PRIMARY
(NAME = ' + @Database + ', FILENAME = ''' + @Path + @Database + '.mdf'', FILEGROWTH = 1024KB)
LOG ON
(NAME = ' + @Database + '_log, FILENAME = ''' + @Path + @Database + '_log.ldf'', SIZE = 5MB,
MAXSIZE = 25MB,
FILEGROWTH = 5MB )
COLLATE SQL_Latin1_General_CP1_CI_AI');
IF @@Error != 0
RAISERROR ('Failed to create database.', 18, 12); -- :Exit(SELECT 2)
所以创建数据库时不需要使用 GO。
在创建架构和填充数据库时,我建议使用 SQL 工具导出脚本,以便最终得到如下所示的脚本:
USE [SpecificDatabase]
/****** Object: ForeignKey [FK_tblAppCustomers_tblCustomers] Script Date: 11/23/2008 12:44:26 ******/
IF EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_tblAppCustomers_tblCustomers]') AND parent_object_id = OBJECT_ID(N'[dbo].[tblAppCustomers]'))
ALTER TABLE [dbo].[tblAppCustomers] DROP CONSTRAINT [FK_tblAppCustomers_tblCustomers]
GO
/****** Object: ForeignKey [FK_tblAppSales_tblGS] Script Date: 11/23/2008 12:44:26 ******/
IF EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_tblAppSales_tblGS]') AND parent_object_id = OBJECT_ID(N'[dbo].[tblAppSales]'))
ALTER TABLE [dbo].[tblAppSales] DROP CONSTRAINT [FK_tblAppSales_tblGS]
GO