我想你已經在錯誤的地方去了。
我使用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
我懷疑你的診斷是錯誤的。對於初學者來說,聲明「不會在SSMS中運行的SQL腳本」需要深入研究。 ['GO'命令](http://msdn.microsoft.com/zh-cn/library/ms188037.aspx)明確是「SQLCMD」的一部分:「GO不是Transact-SQL語句;它是命令可以識別** sqlcmd **和...「 – 2012-08-03 06:44:00