从SQL Server过程调用

时间:2015-08-31 07:43:53

标签: sql-server powershell

我正在尝试设置Powershell脚本来运行一些SQL Server存储过程。最初,脚本返回零或非零返回代码(通过评估catch块),具体取决于过程调用是否失败:

try {
        $command = New-Object System.Data.SqlClient.sqlCommand ("$query", $connection)          
        $DataAdapter = new-object System.data.SqlClient.SqlDataAdapter $command
        $dataset = new-object System.data.Dataset

        $rowCount = $DataAdapter.Fill($dataset)
        if($rowCount -gt 0) {
            $DataAdapter.Fill($dataset) | Out-Null
            $return =,[int]$command.Parameters["@ReturnValue"].Value
            $return += ,$dataset.Tables[0].Rows[0]
        } else{
            $return=,[int]$command.Parameters["@ReturnValue"].Value             
        }
    }
    catch {
        $return=,10000
        throw
    }

现在我想让它更有用,并在作业失败时返回错误消息。为此,我使用System.Data.SqlClient.SqlInfoMessageEventHandler,它似乎工作,除了它不属于catch块,因此不评估其他返回代码。这是代码(完整功能):

function Run-SQLQuery($dataSource, $database, $query) {
$stuffedMessage = ""
$handler = [System.Data.SqlClient.SqlInfoMessageEventHandler] {param($sender, $error) $stuffedMessage +=  "$($_)" };    
try {       
    try {
        $connectionString = "Data Source=$dataSource; " +
            "Integrated Security=SSPI; " +
            "Initial Catalog=$database"

        # Create a connection to the OLAP Database
        $connection = new-object system.data.SqlClient.SQLConnection($connectionString)         
        $connection.add_InfoMessage($handler); 
        $connection.FireInfoMessageEventOnUserErrors = $true;
        $connection.Open()
    }
    catch {
        $return = ,"unable to open connection"
        throw
    }

    try {
        $command = New-Object System.Data.SqlClient.sqlCommand ("$query", $connection)

        $DataAdapter = new-object System.data.SqlClient.SqlDataAdapter $command
        $dataset = new-object System.data.Dataset

        $rowCount = $DataAdapter.Fill($dataset)
        $return = ,$stuffedMessage
        $return +=[int]$command.Parameters["@ReturnValue"].Value
        if($rowCount -gt 0) {

            $DataAdapter.Fill($dataset) | Out-Null
            $return +=[int]$command.Parameters["@ReturnValue"].Value
            $return +=$dataset.Tables[0].Rows[0]
        } else{
            $return +=[int]$command.Parameters["@ReturnValue"].Value                
        }
    }
    catch {
        $return=,10000
        throw
    }       
    $connection.close()
}
catch {
}
Finally
{
    $connection.dispose()
    ,$return
}

我不想评估返回消息以确定proc是否有错误。任何人都可以推荐一种方法或方法来捕获消息,以及一个完整的证明方式来显示proc调用是成功还是失败?

干杯

0 个答案:

没有答案