具有用户定义类型参数的Powershell存储过程

时间:2019-03-04 18:10:28

标签: sql-server powershell

我的SQL Server存储过程如下:

CREATE PROCEDURE ProcessAssessments 
    @assessmentIds AssessmentList READONLY,
    @failed BIT
AS
    UPDATE dbo.table
    SET IsProcessed = 1,
        dbo.ProcessFailed = @failed,
        dbo.ProcessDate = GETDATE()
    WHERE
        dbo.ID IN (SELECT AssessmentId FROM @assessmentIds)
GO

在Powershell中:在全局定义下,我声明了$connectionArrayList

$connection = New-Object System.Data.SqlClient.SqlConnection($connectionString)
$connection.Open()
$processedAssessments.Add("1")
$processedAssessments.Add("2")
$processedAssessments.Add("3")
UpdateAssessments($processedAssessments, 0)

在方法内部,我将ArrayList转换为DataTable,并将其作为参数提供给存储过程。

function UpdateAssessments([System.Collections.ArrayList] $assessments,[bool] $failed) {
    $table = New-Object System.Data.DataTable
    $table.Columns.Add("AssessmentId", "System.String") | Out-Null

    foreach($assessmentId in $assessments) {
        $row = $table.NewRow()
        $row.AssessmentId = $assessmentId
        $table.Rows.Add($row)
    }

    $command = New-Object System.Data.SqlClient.SqlCommand
    $command.CommandType = [System.Data.CommandType]::StoredProcedure
    $command.CommandText = "ProcessKySpecialAssessments"
    $command.Connection = $connection

    $command.Parameters.Add("@assessmentIds", $table)
    $command.Parameters.Add("@failed", $failed)

    $Command.ExecuteNonQuery()
}

但是,执行此操作时,出现以下异常:

  

使用“ 0”参数调用“ ExecuteNonQuery”的异常:“将nvarchar值'System.Collections.ArrayList'转换为数据类型int时转换失败。
  表值参数“ @assessmentIds”的数据与参数的表类型不一致。
  SQL Server错误为:245,状态:1

我真的不确定自己在做什么错。

1 个答案:

答案 0 :(得分:2)

阅读this post后,我更改了SqlParameters,并使其正常工作。

$command.Connection = $connection
    $command.CommandType = [System.Data.CommandType]::StoredProcedure
    $command.CommandText = "ProcessKySpecialAssessments"

    $assessmentIdsParam = New-Object('system.data.sqlclient.sqlparameter')
    $failedParam = New-Object('system.data.sqlclient.sqlparameter')

    $assessmentIdsParam.ParameterName = "assessmentIds"
    $assessmentIdsParam.SqlDBtype = [System.Data.SqlDbType]::Structured
    $assessmentIdsParam.Direction = [System.Data.ParameterDirection]::Input
    $assessmentIdsParam.value = $table

    $failedParam.ParameterName = "failed"
    $failedParam.SqlDBtype = [System.Data.SqlDbType]::Bit
    $failedParam.Direction = [System.Data.ParameterDirection]::Input
    $failedParam.value = $failed

    $command.parameters.add($assessmentIdsParam);
    $command.parameters.add($failedParam);

    $command.ExecuteNonQuery()