4

我有一些将脚本加载到变量的代码,然后我将变量传递给SMO 对象。我得到以下异常:

使用“1”参数调用“ExecuteWithResults”的异常:“数据库'Russell_Test'的执行结果失败。”

  • $serverName 是服务器名称。
  • $databaseName 是数据库名称。
  • $createScript 是读取的脚本。

我该如何解决这个问题?

以下是代码的相关部分。

# 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
    }
4

3 回答 3

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)
于 2013-10-30T21:44:03.743 回答
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();
###############################################################################################
于 2013-11-05T21:24:25.680 回答
1

尝试使用Invoke-SqlCmdcmdlet。此 cmdlet 允许您运行SQLCMD实用程序支持的 T-SQL 代码或命令。

Try{
    Invoke-SqlCmd `
    -Query $createScript `
    -ServerInstance $serverName `
    -Database $databaseName `
    -ErrorAction Stop `
    }
    Catch
    {
        [system.exception]
        $_.Exception | Out-File -Append -FilePath $outputFile
    }
于 2013-11-01T13:06:27.817 回答