我有一个简单的SQL Server存储过程,它接受输入参数并设置输出参数。存储过程的本质如下:
CREATE PROC SomeDB.dbo.SomeProc
@input varchar(255),
@output int OUTPUT
AS
IF @input = 'a'
BEGIN
SET @output = 0;
END
ELSE
BEGIN
SET @output = 1;
END
;
GO
我想在PowerShell中获取@output
变量的值。如果我在SSMS中这样做,我会做类似的事情:
DECLARE @out int;
EXEC SomeDB.dbo.SomeProc 'a', @out OUTPUT;
PRINT @out;
但是,我认为它在PowerShell中并不那么简单。
以下是我在PowerShell中的脚本(我知道它不完整):
$ErrorActionPreference = "Stop"
$server = "some_IP_address"
$db = "SomeDB"
$input = "'a'"
$query = "EXEC dbo.SomeProc $input;"
try {
Invoke-Sqlcmd -ServerInstance $server -Database $db -Query $query -QueryTimeout 60000
} catch {
Write-Host "stored proc error"
}
如何在PowerShell中获取@output
变量的值?
答案 0 :(得分:1)
这样的事可能有用:
$cn = New-Object Data.SqlClient.SqlConnection
$cn.ConnectionString = '...'
$cmd = New-Object Data.SqlClient.SqlCommand
$cmd.CommandText = 'dbo.SomeProc'
$cmd.Connection = $cn
$cmd.CommandType = [Data.CommandType]::StoredProcedure
$p = $cmd.Parameters.Add('@output', '')
$p.Direction = [Data.ParameterDirection]::Output
$p.Size = 42
$cn.Open()
$cmd.ExecuteNonQuery()
$p.SqlValue.Value
[source]