Monday, January 10, 2011

Getting the Output parameter from a Stored Procedure using PowerShell

I might be the only person still supporting SpatialWare for SQL Server, and so this example might only be useful to me and a few others, but the principle is still worth demonstrating.  In SpatialWare, you can check to see if the R-Tree spatial index is created by calling a stored procedure and inspecting the @truth output parameter.  The PowerShell script below shows how you can call the sp_sw_rtree_is_created stored procedure, and get the value of the @truth output parameter.

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "integrated security=SSPI;`
    data source=$ServerName;`
    initial catalog=$DatabaseName;"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "sp_sw_rtree_is_created"
$SqlCmd.Connection = $SqlConnection
$SqlCmd.CommandType = [System.Data.CommandType]'StoredProcedure';
$SqlCmd.Parameters.AddWithValue("@owner", "$OwnerName") >> $null;
$SqlCmd.Parameters.AddWithValue("@table", "$TableName") >> $null;
$SqlCmd.Parameters.AddWithValue("@spatialcolumn", "$SpatialColumn") >> $null;
$SqlCmd.Parameters.AddWithValue("@keycolumn", "$KeyColumn") >> $null;
$outParameter = new-object System.Data.SqlClient.SqlParameter;
$outParameter.ParameterName = "@truth";
$outParameter.Direction = [System.Data.ParameterDirection]'Output';
$outParameter.DbType = [System.Data.DbType]'Boolean';
$SqlCmd.Parameters.Add($outParameter) >> $null;
$SqlConnection.Open();
$result = $SqlCmd.ExecuteNonQuery();
$truth = $SqlCmd.Parameters["@truth"].Value;
$SqlConnection.Close();
$truth;

When you run this PowerShell script, you should get response of True or False depending on whether the R-Tree spatial index is created or not.

1 comment:

Anonymous said...

Thanks! you save my life :-)
Since 2 days, I was trying to get a return value from a Stored Proc... Now I know that you need a new-object System.Data.SqlClient.SqlParameter to get this value!
Happy DBA!