我有一些代码将脚本加载到变量,然后我将变量传递给SMO对象。我得到以下异常:
使用“1”参数调用“ExecuteWithResults”的异常:“执行 数据库'Russell_Test'的结果失败了。 “
如何解决此问题?
以下是代码的相关部分。
# Load Smo and referenced assemblies.
[void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.ConnectionInfo');
[void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.Management.Sdk.Sfc');
[void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO');
[void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMOExtended');
Try{
$server = New-Object Microsoft.SqlServer.Management.Smo.Server $serverName;
$db = $server.Databases.Item($databaseName);
$result = $db.ExecuteWithResults($createScript);
$result | Out-File -Append -FilePath $outputFile;
}
Catch
{
[system.exception]
$_.Exception | Out-File -Append -FilePath $outputFile
}
答案 0 :(得分:5)
以下是如何操作:
# If we cast $Content as a [String], all the newlines are lost
# If we don't cast it, it becomes an array and batching breaks
$Content = (Get-Content $SqlScript) -join [Environment]::NewLine
# When using GO, we must set it up as a StringCollection, not a List or Array
$Batch = New-Object -TypeName:Collections.Specialized.StringCollection
$Batch.AddRange($Content)
$result = $Database.ExecuteWithResults($Batch)
答案 1 :(得分:2)
感谢您的帮助。最终SMO选项不起作用所以我做了这个解决方案:
# Deploy table update scripts
$createScript = Get-Content $scriptFile.FullName | Out-String
################# Script execution to capture errors/messages/warnings ##################
$createScriptList = [regex]::Split($createScript, '\bGO')
$cn2 = new-object system.data.SqlClient.SQLConnection("Data Source=$serverName;Integrated Security=SSPI;Initial Catalog=$databaseName;Connection Timeout=600;Max Pool Size=10");
$cn2.Open();
foreach ($cSL in $createScriptList)
{
Try{
$cmd = new-object system.data.sqlclient.sqlcommand($cSL, $cn2);
$cmd.ExecuteScalar() | Out-File -Append -FilePath $outputFile;
}
Catch
{
[system.exception]
$_.Exception | Out-File -Append -FilePath $outputFile
}
}
$cn2.Close();
###############################################################################################
答案 2 :(得分:1)
尝试使用Invoke-SqlCmd
cmdlet。此cmdlet允许您运行受 SQLCMD 实用程序支持的T-SQL代码或命令。
Try{
Invoke-SqlCmd `
-Query $createScript `
-ServerInstance $serverName `
-Database $databaseName `
-ErrorAction Stop `
}
Catch
{
[system.exception]
$_.Exception | Out-File -Append -FilePath $outputFile
}