如何在 powershell 变量中捕获 PL SQL 函数的输出?

How to capture the output of a PL SQL function in a powershell variable?

我可以使用 powershell 和 sqlplus 连接到远程 oracle 数据库。此外,我还能够将在数据库中执行的 command/query 的输出捕获到 powershell 变量中。 PFB 示例。

$username ="hr"
$password ="hr"
$tnsalias ="orcl"
$outputfilepath="C:\Users\Desktop"

 $sqlquery=@"
 set serveroutput off
 set feedback off
 set heading off
 set echo off
 select sysdate from dual;
"@

运行 以上在oracle数据库中的查询如下

 $xval=$sqlquery | sqlplus -silent $username/$password@$tnsalias
 echo $xval

输出将是

23-APR-18

问题是当我是 运行 PL SQL 函数时,如下所示。

    $sqlquery=@"
     set serveroutput off
     set feedback off
     set heading off
     set echo off
     declare
     x varchar2:=null;     
     exec x:=MYTEST_FUN('a','b');
    "@

$xval 变量中没有捕获值,函数也不是 运行。

如何执行函数,以便在 powershell 变量中捕获函数的 return 值。

一种方法是使其成为 set serveroutput on 并在 BEGIN..END

中使用 DBMS_OUTPUT.PUT_LINE()

另一种选择是使用 sqlplus 的 PRINT 命令。

set serveroutput off
set feedback off
set heading off
set echo off
variable x VARCHAR2  --declare bind variable x
exec  :x := MYTEST_FUN('a','b'); --a colon before x needed.
PRINT x;

为我工作:

$sqlQuery = @"
    set serveroutput off
    set feedback off
    set heading off
    set echo off
    variable x NUMBER;
        select count(*) into :x from TABLE;
    PRINT x;
    exit
"@
($sqlQuery | sqlplus -S user/pass | Write-Output | Out-String).Trim()

迟到,最简洁:

$dateVar = ("set heading off
            select sysdate from dual;" | sqlplus -s $yourConnectionString | Out-String).Trim()