sqlplus statement from command line

SqlOracleSqlplus

Sql Problem Overview


Is it possible to do something like this?

$ sqlplus -s user/pass "select 1 from dual" or
$ echo "select 1 from dual" | sqlplus -s user/pass

I know I can put select 1 from dual in a file and do this:
$ sqlplus -s user/pass @myFile.sql

but I'm wondering if it's actually necessary to create a file just to satisfy sqlplus

Sql Solutions


Solution 1 - Sql

Just be aware that on Unix/Linux your username/password can be seen by anyone that can run "ps -ef" command if you place it directly on the command line . Could be a big security issue (or turn into a big security issue).

I usually recommend creating a file or using here document so you can protect the username/password from being viewed with "ps -ef" command in Unix/Linux. If the username/password is contained in a script file or sql file you can protect using appropriate user/group read permissions. Then you can keep the user/pass inside the file like this in a shell script:

sqlplus -s /nolog <<EOF
connect user/pass
select blah;
quit
EOF

Solution 2 - Sql

I'm able to execute your exact query by just making sure there is a semicolon at the end of my select statement. (Output is actual, connection params removed.)

echo "select 1 from dual;" | sqlplus -s username/password@host:1521/service 

Output:

         1
----------
         1

Note that is should matter but this is running on Mac OS X Snow Leopard and Oracle 11g.

Solution 3 - Sql

My version

$ sqlplus -s username/password@host:port/service <<< "select 1 from dual;"


         1
----------
         1

EDIT:

For multiline you can use this

$ echo -e "select 1 from dual; \n select 2 from dual;" | sqlplus -s username/password@host:port/service


         1
----------
         1


         2
----------
         2

Solution 4 - Sql

I assume this is *nix?

Use "here document":

sqlplus -s user/pass <<+EOF
select 1 from dual;
+EOF

EDIT: I should have tried your second example. It works, too (even in Windows, sans ticks):

$ echo 'select 1 from dual;'|sqlplus -s user/pw

         1
----------
         1


$

Solution 5 - Sql

For windows version you can try below. remove double quotes (")

echo select 1 from dual; | sqlplus -s username/password@service

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionandersonbd1View Question on Stackoverflow
Solution 1 - SqlDavid MannView Answer on Stackoverflow
Solution 2 - SqlGrant LammiView Answer on Stackoverflow
Solution 3 - SqlrofrolView Answer on Stackoverflow
Solution 4 - SqlDCookieView Answer on Stackoverflow
Solution 5 - SqlVinodraj JayaramanView Answer on Stackoverflow