【问题标题】:How to capture the output of a PL SQL function in a powershell variable?如何在 powershell 变量中捕获 PL SQL 函数的输出?
【发布时间】:2018-04-23 15:55:59
【问题描述】:

我可以使用 powershell 和 sqlplus 连接到远程 oracle 数据库。此外,我还能够将数据库中执行的命令/查询的输出捕获到 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 变量中捕获函数的返回值。

【问题讨论】:

    标签: oracle powershell plsql sqlplus


    【解决方案1】:

    一种方法是使其成为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;
    

    【讨论】:

    • 通过打印绑定变量值,我可以将它捕获到一个 powershell 变量中。
    • @rainu :我忘了提一件事。您还应该更喜欢以适当的大小声明 VARCHAR2 以适合您的输出,例如 VARCHAR2 (10)
    • 是的,我必须这样做。
    【解决方案2】:

    为我工作:

    $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()
    

    【讨论】:

      【解决方案3】:

      迟到,最简洁:

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

      【讨论】:

        猜你喜欢
        • 2015-03-07
        • 2012-05-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-30
        • 1970-01-01
        • 1970-01-01
        • 2011-12-27
        相关资源
        最近更新 更多