What's the proper syntax for writing stored procedures in sqlplus? The internet is surprisingly unhelpful on this point since SQL tutorials don't seem to specify their environment, or the example they give is a little confusing. I think the simplest way to figure this is that I'll post two commands (out of several I need to make), and if someone can write what they'd look like as stored procedures, I'm sure I can figure the rest out on my own.
Command 1:
code:
SELECT COUNT(username)
FROM "ValidClients"
WHERE username = [username goes here];
Command 2:
code:
INSERT into "ValidClients"
/*zero is overridden by a sequence trigger*/
VALUES (0, [username], [password]);
As you can see, it's really basic stuff, I'm just used to Microsoft SQL Server and so SQLPlus syntax is tripping me up a little. Thanks in advance.
Here's an example from Google:
CREATE PROCEDURE addtuple1(i IN NUMBER) AS
BEGIN
INSERT INTO T2 VALUES(i, 'xxx');
END addtuple1;
The entire tuturial looks kindof nice.
Related
Folks could someone please share the ways to debug a Stored Proc ? It was an interview question where the interviewer was asking the way to debug a SP without using tools. Finally he said like, in Oracle, there is something in a package which gives a way to debug. I didn't understood neither he completely explained :(
well, if you are on SSMS, the easiest way would be to use the print function. Each line you want to see if ti was "reached", just add a print 'line X' and check your messages tab.
If you are not on SSMS, you can create a global temp table (create table ##debug_table....) and add insert statments in your proc folowing the same logic as the prints.
All of these "solutions" are considering that you have permisison to update the proc, of course. If yo udont I really dont see how it could be done.
I have a cursor which returns two values: one which I will use (and therefore will assign to an out variable) and another which I've only had returned to make the ROWNUM thing work.
If I run the cursor as a query, it works as expected. But if I execute the procedure the out variable comes empty. Is my approach somehow not supported? I mean, returning two values but only using one of them?
Here is my procedure code: (Don't delve too much on the query itself. It works, I know it's a bit ugly but it works. It was the only way I found to return the second-last row)
procedure retorna_infos_tabela_164(i_nip in varchar,
o_CODSDPANTERIOR out number) is
cursor c_tabela_164 is
select *
from(
select CODSDP,ROWNUM rn
from
(
select NRONIP,CODTIPOMOV,CODSDP
from TB164_HISTORICOMOVIMENTACOES
where NRONIP = i_nip and
CODTIPOMOV='S1'
order by DTHMOV desc
)
)
where rn=2;
v_temp_nr number;
begin
open c_tabela_164;
fetch c_tabela_164 into o_CODSDPANTERIOR,v_temp_nr;
close c_tabela_164;
end retorna_infos_tabela_164;
EDIT The way I've tried to run this procedure was by dbms_output.put_line(o_CODSDPANTERIOR) which didn't work. Then I googled a little bit and saw I should TO_CHAR() my var first and then have it output. Didn't work either.
There's no problem with passing a number to DBMS_OUTPUT.PUT_LINE. Oracle will silently convert other built-in types to VARCHAR2 using the default format. You only need to use TO_CHAR if you want to control the format used -- which is often a good idea, but not generally necessary.
One possibility, though, is that you are not seeing the output because you have not enabled it. If you are running your test in SQLPlus, make sure you SET SERVEROUTPUT ON before running code that includes DBMS_OUTPUT calls. If you are using some other client, consult its documentation for the proper way to enable DBMS_OUTPUT. (You can of course test if it's enabled by adding another call to output a string literal.)
There's nothing inherently wrong with the technique you're using to populate the out parameter. However, it's not necessary to return two columns from the cursor; your select * could simply be select CODSDP. You seem to be under the misconception that any column referenced in the predicates has to be in the select list, but that's not the case. In your innermost query, the select list does not need to include NRONIP or CODTIPOMOV, because they are not referenced in the outer blocks; the WHERE clause in that query can reference any column in the table, regardless of whether it is in the select list.
So, my first guess is that you simply don't have server output enabled. The only other possibility I can think of right now is that you're running your query and the procedure in two different sessions, and one of them has uncommitted transaction against the table, so they are actually seeing different data.
If those suggestions don't seem to be the problem, I'd suggest you run your tests of the standalone query and the procedure in a single SQLPlus session, then copy and paste the entire session here, so we can see exactly what you're doing.
I'm sorry I've had you guys take the time to answer me when the answer was something to do with the tool I'm using. I hope all you guys have learnt something.
The query does work for me at least, I've not come across any edge cases where it doesn't work, but I haven't tested it exhaustively.
The problem was that TOAD, the tool I'm using to run the procedures, sometimes populates the procedures with the parameters I tell it to but sometimes it doesn't. The issue here was that I was trying to execute the procedure with no parameters, yielding no results...
Lesson Learnt: double check the generated procedure code when you run a Procedure using Right Click > Run Procedure on TOAD version 9.
My assignment is to write a PLSQL module to insert data into database. Upon a certain condition, it may need additional information and should prompt the user for one more detail. This should be done directly in PLSQL and wording is straight from the assignment.
I've researched the topic and found some people said this cannot be done in PLSQL? But the ACCEPT PROMPT function does exist.
ACCEPT v_string PROMPT 'Enter your age: ';
While this works directly from SQLPlus, it does not work in PLSQL as it gives me this error:
PLS-00103: Encountered the symbol "V_STRING" when expecting one of the following: := . ( # % ;
Can anyone provide some insight as to how I'm supposed to ask the user from PLSQL, only upon when a certain condition is true (the condition is checked when you get something else from the DB). To clarify, I only need help on how to accept input.
Thanks for your time.
There is a trick that will allow you to do something like this, but (a) it's a bit of a hack, (b) you need to be logged into the database server itself, and (c) it only works on Linux (and perhaps other flavours of Unix).
Generally, it's not possible to ask for user input in PL/SQL, especially if you're connecting to a database on a remote machine. Either your assignment is wrong or you've misunderstood it.
PL/SQL programs are designed to run on the database server, so it doesn't make sense to ask the user for input during them. Using the ACCEPT command, SQL*Plus can ask the user for input while running a script client-side. SQL*Plus will then substitute in the value entered before sending SQL or PL/SQL to the database.
Well, since it's not really a part of SQL, but rather the developer tools you use, here's the ones I know:
SQL*Plus: &Variable
SQL Developer: You can make a procedure or you can use :Variable to be prompted to insert a parameter
I checked and tried following things which might helpful to you. It's just an example which I tried. You can implement your own logic.
declare
c1 varchar2(50);
begin
c1:='&enter_value';
dbms_output.put_line(c1);
exception
when others then
dbms_output.put_line(sqlerrm);
end;
'&' will help you to prompt and ask input to user. Once user feeds some input, it will assign to variable and you can use variable wherever you want.
Hopefully this helps you.
You cannot get user input in pure PL/SQL. It is a server-side language to express business/database logic.
The use of "&" to get input is a "sqlplus" feature and not a PL/SQL strategy. If it was an "assignment" then you need to tell the teacher that it is an invalid assignment - or maybe it was a trick question!
Does anyone have some code to simply log some detailed information to a file within a SQL query (or stored procedure or trigger)? I'm not looking for anything fancy. All I want to do is to quickly put debug information into my SQL, much like folks do for JavaScript debugging using alerts. I looked at using Lumigent, but that seems like overkill for what I want to do. I don't care what the format of the logging is in. Below is a simple example of what I'd like to do.
Example:
DECLARE #x int;
SET #x = '123'
-- log the value of #x
============
9/6/2011 # 4:01pm update
I tried the sqlcmd below, which works well. But it doesn't work well when there are 100 parameters on a stored procedure when I want to debug. In that case, I need to go put a break-point in my client code, then get the value of each argument. Then go and type out the exec command, and then look at the output file. All I want to do is put one simple line of code into my SQL (perhaps calling another stored procedure if it takes more than one line of code), that writes a variable value to a file. That's it. I'm just using this for debugging purposes.
One pretty easy method is to use either OSQL or SQLCMD to run your procedure. These are command-line methods for executing SQL commands/procedures/scripts.
With those utilities you can pipe the output (what would normally appear in the "Messages" tab in SSMS) to a text file.
If you do this, in your example the code would be:
DECLARE #x int;
SET #x = '123'
PRINT #x
If you are running the same procedure multiple times, you can just save it a a one-line batch file to make it very easy to test.
Now with more background I think I can promote my comment to an answer:
Why does it have to be a file? If this is just during debugging, can't you just as easily log to a table, and when you want to see the recent results:
SELECT TOP (n) module, parameters, etc.
FROM logTable
ORDER BY DateCreated DESC;
You can simplify the logging or at least make it easier to replicate from procedure to procedure by having a stored procedure that takes various arguments such as ##PROCID and others to centralize the logging. See this article I wrote for some ideas there - it's geared to just logging once per stored procedure call but you could certainly call it as often as you like inside any stored procedure.
This seems like much less hassle than using an archaic file-based log approach. You're already using a database, take advantage!
If you're committed to using a file for whatever reason (it might help to understand or counter if you enumerate those reasons), then the next best choice would likely be CLR, as already mentioned. A complete solution in this case might be beyond the scope of this single question, but there are tons of examples online.
I am looking for good resources on Oracle Stored Procedure geared towards beginners. I tried the Dev Shed Article and one from Oracle Documentation site but they did not meet my needs. The one form Oracle Documentation site had the overhead of Java example. I tried the Dev Shed one but I keep getting invalid SQL error when I try their example. Here is the basic one that I tried to run:
CREATE OR REPLACE PROCEDURE skeleton
IS
BEGIN
NULL;
END;
EXECUTE skeleton;
Am I making a rookie mistake or is the syntax in the article out of date? I am working with Oracle 10g & PL/SQL Developer.
Thanks!
SOLUTION:
As per #curtisk's suggestion, I tried a slightly more involved example:
CREATE OR REPLACE PROCEDURE p_getdate
IS
BEGIN
dbms_output.put_line(TO_CHAR
(SYSDATE, 'MM-DD-YYYY HH24:MI:SS'));
END;
When I tried to execute it like so:
EXECUTE p_getdate
I got ORA-00900: Invalid SQL statement error. I looked for why this would be the case & stumbled across this thread. I decided to give call a try so I tried the following:
CALL p_getdate;
but that did not work as well. I read the thread some more & skeptically tried:
CALL p_getdate();
and voila, I had the procedure being called properly. I do not have an answer as to why this works but the fact that it works allows me to move forward with my project. If there is anyone who can explain to me why this is, I would love to learn more on this.
Thanks once again to #curtisk for the help!
I wouldn't use that example as a starting point...I'd make it do something here's one to try
CREATE OR REPLACE PROCEDURE p_getdate
IS
BEGIN
dbms_output.put_line(TO_CHAR
(SYSDATE, 'MM-DD-YYYY HH24:MI:SS'));
END;
Run that, it should compile successfully, then at the prompt....
SQL> SET SERVEROUT ON;
SQL> execute p_getdate;
06-11-2009 12:29:54
You should see the current date/time in the output. The example you used was too simple IMHO. Next step is to create a procedure that deals with declarations and parameters.
As far as beginner resources, there's a ton out there can't really recommend any one in particular, and if nothing there's always "Ask Tom"..should be some Q/A there that may help
Your best bet would be a book such as Oracle PLSQL Programming by Steve Feurenstein and Bill Prybil. This has tons of examples and is around 1300 pages.
If you just need a reference, you can try this url to the oracle 12c plsql language reference, though I'm a bigger fan of use cases as found in the previous suggestion.
http://docs.oracle.com/database/122/LNPLS/toc.htm