如何使用Powershell将存储过程输出参数转换为变量?

How to get stored procedure output parameter into variable using Powershell?

我有一个返回字符串的存储过程,我需要将结果作为 powershell 变量。我坚持输出参数语法。

Powershell 脚本:

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=myserver;Database=mydb;Integrated Security=True"
$SqlConnection.Open()
$SqlConnection.State

$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "testsp3"
$SqlCmd.Connection = $SqlConnection


$op = new-object System.Data.SqlClient.SqlParameter;
$op.ParameterName = "@answer";
$op.Direction = [System.Data.ParameterDirection]'Output';
$op.DbType = [System.Data.DbType]'String';
$op.Size = 2500

$SqlCmd.Parameters.Add($op);

$what = $SqlCmd.ExecuteScalar();

$what

错误信息:

Exception calling "ExecuteScalar" with "0" argument(s): "Procedure or function 'testsp3' expects parameter '@answer', which was not supplied."

存储过程如果重要:

CREATE PROCEDURE [dbo].[testsp3]
@answer nvarchar(max) output

AS
BEGIN
    SET NOCOUNT ON;

    SELECT @answer = 'blah blah blah'
    RETURN
END
GO

修改你的脚本如下

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=myserver;Database=mydb;Integrated Security=True"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "testsp3"
$SqlCmd.Connection = $SqlConnection
$SqlCmd.CommandType = [System.Data.CommandType]'StoredProcedure'; <-- Missing
$outParameter = new-object System.Data.SqlClient.SqlParameter;
$outParameter.ParameterName = "@answer";
$outParameter.Direction = [System.Data.ParameterDirection]'Output';
$outParameter.DbType = [System.Data.DbType]'String';
$outParameter.Size = 2500;
$SqlCmd.Parameters.Add($outParameter) >> $null;
$SqlConnection.Open();
$result = $SqlCmd.ExecuteNonQuery();
$truth = $SqlCmd.Parameters["@answer"].Value;
$SqlConnection.Close();
$truth;