У меня есть простой файл SQL, который создает новую базу данных на основе 3 отправленных входных параметров: dbName, datafileName и logfileName
Но когда я вызываю этот скрипт через powershell, вызывая командлет Invoke-Sqlcmd, я получаю следующую ошибку:
Incorrect syntax near 'CommonDB'.
Incorrect syntax near '\'.
Incorrect syntax near 'CommonDB'.
Incorrect syntax near 'E:'.
The label 'E' has already been declared. Label names must be unique within a query batch or stored procedure.
Incorrect syntax near 'E:'.
The label 'E' has already been declared. Label names must be unique within a query batch or stored procedure.
Incorrect syntax near 'CommonDB'.
The label 'E' has already been declared. Label names must be unique within a query batch or stored procedure.
The label 'E' has already been declared. Label names must be unique within a query batch or stored procedure.
At line:1 char:1
+ Invoke-Sqlcmd -ServerInstance localhost\sql2012 -Database master -Use ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Invoke-Sqlcmd], SqlPowerShellSqlExecutionException
+ FullyQualifiedErrorId : SqlError,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand
Моя версия Powershell:
Major Minor Build Revision
----- ----- ----- --------
5 1 16299 1004
Это мой файл CreateDatabase.sql:
USE MASTER
GO
SET QUOTED_IDENTIFIER ON;
GO
DECLARE
@DbName nvarchar(50),
@sql nvarchar(max),
@datafileName nvarchar(500),
@logfileName nvarchar(500)
SET @sql = N''
SELECT @DbName = N'$(dbName)'
SELECT @datafileName = N'$(datafileName)'
SELECT @logfileName = N'$(logfileName)'
IF NOT EXISTS (SELECT * FROM master.sys.databases WHERE name = @DbName)
BEGIN
SELECT @sql =
N'CREATE DATABASE "' + @DbName + N'"'
+ N' ON PRIMARY ( NAME = [' + @DbName + '] ,'
+ N' FILENAME = [' + @datafileName + '],'
+ N' SIZE = 1GB , MAXSIZE = UNLIMITED, FILEGROWTH = 512MB )'
+ N' LOG ON ( NAME = [' + @DbName + '_log] ,'
+ N' FILENAME = [' + @logfileName + '], SIZE = 100MB , FILEGROWTH = 10% )'
END
IF (@sql <> N'')
EXEC (@sql)
GO
SET QUOTED_IDENTIFIER OFF;
GO
Это мой файл PS1 Содержание:
$params=@("dbName='CommonDB'", "datafileName='E:\my files\sql.2012\data\CommonDb.mdf'", "logfileName='E:\my files\sql.2012\data\CommonDb_log.ldf'")
Invoke-Sqlcmd -ServerInstance localhost\sql2012 -Database master -Username sa -Password xxxx -ErrorAction Stop -InputFile .\CreateDatabase.sql -Variable $params
Но, если я запускаю это из приглашения PS, он работает просто отлично:
PS E:\My Scripts> Invoke-Sqlcmd -ServerInstance localhost\sql2012 -Database master -Username sa -Password xxxx -ErrorAction Stop -InputFile .\CreateDatabase.sql -Variable dbName='CommonDB', datafileName='E:\my files\sql.2012\data\CommonDb.mdf', logfileName='E:\my files\sql.2012\data\CommonDb_log.ldf'