11

I have a stored procedure returning a string and I need the result as a powershell variable. I'm stuck on the output parameter syntax.

Powershell script:

$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

Error message:

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

Stored procedure if it matters:

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

AS
BEGIN
    SET NOCOUNT ON;

    SELECT @answer = 'blah blah blah'
    RETURN
END
GO
scw
  • 5,450
  • 8
  • 36
  • 49

1 Answers1

22

Modify your script to be like below

$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;
Rahul
  • 76,197
  • 13
  • 71
  • 125
  • 1
    Yep, that's what you were missing; I also added the line for capturing the output variable. – Rahul Jun 17 '15 at 19:08
  • 1
    +1 for this line $SqlCmd.Parameters.Add($outParameter) >> $null. This helped me with another question I had about how to clean out unwanted items from the pipeline. Thanks @Rahul. – The Dumb Radish Mar 17 '16 at 17:11
  • 1
    Don't forget to check the available constructors for [System.Data.SqlClient.SqlParameter](https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparameter%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396). You can save some typing by setting the parameter values on instantiation that way. – Mark Iannucci Jan 25 '17 at 21:43