Tom Troughton
Tom Troughton

Reputation: 4325

How to call a stored procedure with a char parameter from Powershell

I have a Powershell script which I want to execute a SQL Server stored procedure. The stored procedure has a parameter named @backupType which of a CHAR(1) type. I'm calling it like this:

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=(local);Database=master;Integrated Security=True"
$SqlConnection.Open()
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "sp_myStoredProcedure"
$SqlCmd.Connection = $SqlConnection

$SqlCmd.Parameters.Add("@backupType", [System.Data.SqlDbType]"Char", 1)
$SqlCmd.Parameters["@backupType"].Value = "F"

$result = $SqlCmd.ExecuteNonQuery()
$SqlConnection.Close()

The error I get is:

Exception calling "ExecuteNonQuery" with "0" argument(s): "Procedure or function 'sp_myStoredProcedure' expects parameter '@backupType', which was not supplied." At line:14 char:1

  • $result = $SqlCmd.ExecuteNonQuery()
  • ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    • CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    • FullyQualifiedErrorId : SqlException

I can only assume I'm specifying the parameter wrong but a Google and search of SO has not surfaced anything helpful. Any ideas?

Upvotes: 1

Views: 472

Answers (1)

Esperento57
Esperento57

Reputation: 17472

try with

$SqlCmd.CommandType = [System.Data.CommandType]::StoredProcedure
$SqlCmd.Parameters.Add("@backupType", [System.Data.SqlDbType]::Char, 1).Value="F"

Upvotes: 1

Related Questions