I want to be able to insert a variable number of rows into a table based on user input? eg.
Please enter value, enter "done" when no more values: value 1
Please enter value, enter "done" when no more values: value 2
Please enter value, enter "done" when no more values: done
2 Rows inserted successfully.
I'm not sure how to store the rows temporarily and I'm not sure how to ask the user multiple times to insert data. Does pl/sql have arrays?
Thanks
Most likely, you can't, at least not without writing some sort of client application (not a
SQL*Plus
script).PL/SQL
runs on the server and has nothing to accept user input.SQL*Plus
runs on the client but it has no looping constructs. You can't mix the two, so you can't have a PL/SQL loop that happens repeatedly prompts the user for input and does an INSERT based on the values passed in.Most commonly, people get around this by writing a small front-end script in your favorite scripting language that gathers the input and then issues appropriate INSERT statements.
If you really, really want to accomplish the task in
SQL*Plus
, it is probably possible, but quite painful. You would basically have to construct an infinite loop that you threw an error to escape from. For exampleDefine a script a.sql (I happen to store mine in c:\temp)
And then in
SQL*Plus
Horribly ugly, of course, but it "works" for some definition of "works"
I'd recommend Oracle Application Express. It's free, and dead easy to build simple apps very quickly.
Sure, it may be overkill for your extremely simple requirement here, but chances are someone will come back and say "I loved your little SQL*Plus script - could you just add a few more features to it" and before you know it you're building a skyscraper with a shack foundation.
I think you're pounding a nail with a screwdriver.
You'd get far more flexibility using a Python script, a PHP page, a Perl script, a Java program, or any other environment that can access Oracle.
As others have said, PL/SQL alone is not suitable for this task, you need a UI on top to interact with the end user. However, if you have a real need to do this in SQL Plus, it is possible using the technique I described in this SO question.
You need to create 2 SQL Plus scripts:
1) A script to perform a single insert, here called script_insert.sql:
2) A script to control the process, here called main.sql:
Now in SQL Plus you can run it like this:
Let me reiterate that this demonstrates it can be done, I would not claim it to be a good way to implement the requirement - unless it is just an ad hoc tool to be used by a DBA or developer. I would never give an end user SQL Plus as a UI!
Maybe you can have your user enter a comma seperated list of values?
Then process the string in your plsql block.