我有一个返回字符串的存储过程,我需要将结果作为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
错误讯息:
异常调用" ExecuteScalar"用" 0"参数:"程序或功能' testsp3'期望参数' @ answer',这是未提供的。"
存储过程如果重要:
CREATE PROCEDURE [dbo].[testsp3]
@answer nvarchar(max) output
AS
BEGIN
SET NOCOUNT ON;
SELECT @answer = 'blah blah blah'
RETURN
END
GO
答案 0 :(得分:9)
将您的脚本修改为如下所示
$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;