I've been reading some questions on SO about how to query an Oracle database with a batch script, such as this one.
This command seems to work well to get the result of a single query:
<query>; | sqlplus <username>/<password>@<database>
But can I modify this such that:
A connection to the database and the query are separate commands
I can use this command in a loop. (This command doesn't seem to work well in loops. I keep getting an error that the
|
character was not recognized.)
A bit of context as to what I'm trying to accomplish:
I have a text file which contains a list of table names and column names in my Oracle database, e.g. the contents of this file would be:
table1, columnA
table1, columnB
table2, columnC
table2, columnD
I want to query the database to look at every table/column pair in this file and return the datatype and data precision.
I don't need help with the actual query. This is the query that gives the results I need:
SELECT DATA_TYPE,DATA_PRECISION FROM ALL_TAB_COLUMNS
WHERE TABLE_NAME='<tableName>' AND COLUMN_NAME='<columnName>';
And the reason I want to have a separate command for database connection and database query is because, since multiple queries will be called, it makes sense to only connect to the database once, perform all the queries, and then quit the connection.
Something like this seems to be what I want to accomplish, but it isn't working properly. See below my current batch script.
REM Required for dynamic values in for loop
setlocal enabledelayedexpansion
REM For all of the lines in my input text file
for /f "tokens=1,2 delims=, " %%i in (inputFile.txt) do (
REM Store column name and table name
set tableName=%%i
set columnName=%%j
REM Perform query
for /f "tokens=1,2 skip=2" %%k in ('SELECT DATA_TYPE,DATA_PRECISION FROM ALL_TAB_COLUMNS WHERE TABLE_NAME=''!tableName!'' AND COLUMN_NAME=''!columnName!''; | sqlplus <username>/<password>@<database>') do (
REM Only care about first result, since it will only return one row
set dataType=%%k
set dataPrecision=%%l
REM Process dataType and dataPrecision as necessary
REM ...
)
)