Config SQL*Plus to return nothing but data

前端 未结 2 2023
情话喂你
情话喂你 2021-01-06 09:32

I need to write a simple shell function that returns a single field from an Oracle DB. Think of it as for example SELECT \'ABC\' FROM dual; and ABC is what I a

相关标签:
2条回答
  • 2021-01-06 10:12

    There are a few different approaches in this askTom thread on returning values from SQL*Plus to a shell script.

    One common approach is to select a constant token in addition to the value that you want to return (in Tom's example, that is the string "KEEP") and then use sed (or your favorite command-line parser) to extract the data you're actually interested in

    #!/bin/ksh
    
    x=`sqlplus / <<endl | grep KEEP | sed 's/KEEP//;s/[   ]//g'
    select 'KEEP' , max(sal) from emp;
    exit
    endl`
    
    echo the answer is $x
    

    Other approaches, such as approaches that allow you to read multiple lines of output are also discussed in that thread.

    If you don't want the header to be printed, you should be specifying

    set head off
    

    in your SQL*Plus script-- I'm not sure why you're explicitly setting the header on in the script if you don't want the header... Do you want to keep some part of the header?

    0 讨论(0)
  • 2021-01-06 10:34

    Based on Justin's answer (which is great), when you only need to select one number (or token), I consider this a little shorter, yet more readable version:

    x=`sqlplus -S / <<< "select 'KEEP' , max(sal) from emp;" | awk '/KEEP/{print $2}'`
    
    0 讨论(0)
提交回复
热议问题