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

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (46)

我的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:在全球定义下,我宣布$connection,和ArrayList

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

在Method的内部,我将转换ArrayList为a 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

我真的不确定我做错了什么。

提问于
用户回答回答于

阅读这篇文章后,我改变了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()

扫码关注云+社区

领取腾讯云代金券