cant compile any cursor example - sql

I'm trying to make any cursor example working, but just cant make it happen.
IDE: Oracle SQL developer
database: 10g sql oracle
I've tried this three examples, but it didn't compile well. Can someone provide me with working examples?
First one:
EDIT: works! just had 'where where'
DECLARE
CURSOR person_data_cur
as
SELECT *
FROM personal_data
WHERE where name='Karol';
BEGIN
FOR person_data
IN person_data_cur
LOOP
DBMS_OUTPUT.put_line (
person_data.surname);
END LOOP;
END;
and this:
DECLARE my_cursor1 CURSOR FOR
SELECT name, surname
FROM personal_data
WHERE name='Karol';
^error:
Error report -
ORA-06550: row 1, column 27:
PLS-00103: found symbol "FOR" when expected one of following:
:= . ( # % ; not null range default character
06550. 00000 - "line %s, column %s:\n%s"
*Cause: Usually a PL/SQL compilation error.
*Action:
or even this:
EDIT: this one is OK, just my IDE ignored first two lines, and executed others... but i guess it was OK since it wasnt inside any block or procedure
CURSOR c1
IS
SELECT course_number
FROM courses_tbl
WHERE course_name = name_in;

For Second Example : Your syntax is incorrect.
The pseudo code for the cursor is :
Declare
Cursor Cursor_name
is
select * from table where <Conditions>;
Begin
For cur_Rec in cursor_name
Loop
<what you want to do>
End Loop;
End;
For the third example, I believe name_in is an input parameter, please correct the syntax to :
CURSOR c1 (name_in VARCHAR2)
IS
SELECT course_number
FROM courses_tbl
WHERE course_name = name_in;
Please refer Cursor Declaration for more details

Related

Oracle SQL Using Variables Not Running

This is probably an elementary question, but I'm new to Oracle SQL. I'm trying to get the SQL below to execute in Oracle SQL Developer. The error information is below the code. I've modified the code since I pasted the error message. Line 28 is the last line in the code, "END;" Line 14 column 1 refers to the word "Select".
DECLARE
v_StartDate Date := &StartDate;
v_EndDate Date := &EndDate;
SET v_StartDate := CASE &StartDate
WHEN TO_DATE('01/01/1900','MM/DD/YYYY')
THEN LAST_DAY(ADD_MONTHS(trunc(current_date),-2))
ELSE TO_DATE(&StartDate - 1) END;
SET v_EndDate := CASE &StartDate
WHEN TO_DATE('01/01/1900','MM/DD/YYYY')
THEN LAST_DAY(ADD_MONTHS(&EndDate,-1))
ELSE TO_DATE(&EndDate + 1) END;
BEGIN
Select *
From
Table
Where date_value > v_StartDate
and date_value < v_EndDate
END;
Error report -
ORA-06550: line 28, column 24:
PL/SQL: ORA-00933: SQL command not properly ended
ORA-06550: line 14, column 1:
PL/SQL: SQL Statement ignored
ORA-06550: line 28, column 27:
PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following:
( begin case declare end exception exit for goto if loop mod
null pragma raise return select update while with
<< continue close current delete fetch lock
insert open rollback savepoint set sql execute commit forall
merge pipe purge json_exists json_value json_query
json_object json_array
06550. 00000 - "line %s, column %s:\n%s"
*Cause: Usually a PL/SQL compilation error.
*Action:
There are several things wrong with your code. I suggest you start with a small piece of code that works and then add statement by statement. That will allow you to see what is wrong and fix it. Once you have an accumulated set of syntax errors it becomes difficult to debug.
There are comments where the code has errors:
DECLARE
v_StartDate Date := &StartDate;
v_EndDate Date := &EndDate;
-- issues below:
-- 1. SET is not oracle syntax. To assign a variable, use the := operator
-- without the SET word.
-- 2. you cannot assign variables in the declaration section, unless you
-- declare and assign in the same statement. This part should go after
-- the BEGIN keyword
-- 3. Why would you use the bind variable if you already assigned it
-- above ??
SET v_StartDate := CASE &StartDate
WHEN TO_DATE('01/01/1900','MM/DD/YYYY')
THEN LAST_DAY(ADD_MONTHS(trunc(current_date),-2))
ELSE TO_DATE(&StartDate - 1) END;
SET v_EndDate := CASE &StartDate
WHEN TO_DATE('01/01/1900','MM/DD/YYYY')
THEN LAST_DAY(ADD_MONTHS(&EndDate,-1))
ELSE TO_DATE(&EndDate + 1) END;
BEGIN
-- issue below
-- you cannot just select in pl/sql, you need to SELECT INTO (if there is
-- a single row) or BULK COLLECT INTO (if you have multiple rows)
Select *
From
Table
Where date_value > v_StartDate
and date_value < v_EndDate
END;
I'm sorry to have to say it, but your code "has more errors than an early Met's game".
The key word SET belongs as a clause of the UPDATE statement. You have to UPDATE statements. If you just want to set the value of a variable, the syntax is simply
v_StartDate := some_value
And you have already set the value of v_StartDate with a parameter in you DECLARE section, so what are you trying to do with it now?
The keyword WHEN requires a comparison, but your usage
WHEN TO_DATE('01/01/1900','MM/DD/YYYY')
THEN LAST_DAY(ADD_MONTHS(trunc(current_date),-2))
Is not comparing the first arugment (TO_DATE ....) with anything.
You are trying to trunc(current_date) but 'current_date' is not defined -- and it's not a key word or reserved word. Perhaps you meant 'sysdate'.

Invalid identifier error while running plsql block

Since my school does not allow me to post the code, hence i had to come back home and put up an example to show the issue i am facing. My school asked me to do a homework on dynamic sql to create a table and later insert one dummy record to it. But while doing it I am facing the below issue. Please find the code below for your reference. Thank you.
Procedure:
create or replace procedure table_creation(table_name in varchar2,col1 varchar2,col2 varchar2)
is
l_stat varchar2(3000);
v_stat varchar2(1000);
a varchar2(10):='1';
b varchar2(10):='Dummy';
begin
l_stat:='create table '||table_name||' ("'||col1||'" varchar2(10),"'||col2||'" varchar2(10))';
execute immediate l_stat;
execute immediate 'insert into '||table_name||'('||col1||','||col2||') values (:x,:y)' using a,b;
end;
/
Plsql Block to call the procedure:
set serveroutput on;
declare
a varchar2(10);
b varchar2(10);
c varchar2(10);
begin
a:='Example';
b:='id';
c:='nm';
table_creation(a,b,c);
dbms_output.put_line('Yes');
end;
/
The procedure is getting created perfectly and while running the above block i am getting the below error .
declare
*
ERROR at line 1:
ORA-00904: "NM": invalid identifier
ORA-06512: at "SYS.TABLE_CREATION", line 9
ORA-06512: at line 9
But when I checked the created table. The table exists with 0 records. The structure of the table is as follows.
Name Null? Type
----------------------------------------- -------- ---------------
ID VARCHAR2(10)
NM VARCHAR2(10)
Any help from your end is much appreciated.
Nick,
Please note that the above procedure will create the column with a double qoutes ("ID","NM") hence the error occurred. Please find the updated code and check if the issue has resolved.
According to oracle=>
Oracle is case sensitive in column and table names. It just converts everything to upper case by default. But if you use names in double quotes, you tell Oracle to create the column in the exact spelling you provided (lower case in the CREATE statement).
Code:
create or replace procedure table_creation(table_name in varchar2,col1 varchar2,col2 varchar2)
is
l_stat varchar2(3000);
v_stat varchar2(1000);
a varchar2(10):='1';
b varchar2(10):='Dummy';
begin
l_stat:='create table '||table_name||' ('||col1||' varchar2(10),'||col2||' varchar2(10))';
execute immediate l_stat;
execute immediate 'insert into '||table_name||'('||col1||','||col2||') values (:x,:y)' using a,b;
end;
/
Note: I have not touched any other logic of the code. Please try and let us know the result.
Only change is
From :
l_stat:='create table '||table_name||' ("'||col1||'" varchar2(10),"'||col2||'" varchar2(10))';
to :
l_stat:='create table '||table_name||' ('||col1||' varchar2(10),'||col2||' varchar2(10))';

How to create a Trigger in oracle?

I have oracle database 11gR2 and i want to create some triggers automatically with a block .
when i want to run query in below , i have an error .
My block is :
declare
tablesid number ;
tablenames varchar2(4000);
cursor c1 is
select id , title from hr.tables;
begin
open c1;
loop
fetch c1 into tablesid , tablenames;
CREATE OR REPLACE TRIGGER tablenames||'_before_insert'
before insert
on hr.tablenames
DECLARE
columnid number ;
columnval number ;
columntitle varchar(4000);
cursor c2 is
select id from hr.columns where tableid = tablesid ;
BEGIN
-- open c2 ;
for rec in c2 loop
select title into columntitle from hr.columns where id = rec.id
insert into hr.rowaction(columnid,newvalue,oldvalue,actiondate)
(
select id ,:new.columntitle,:old.columntitle,sysdate
from hr.tabletiltes
where id = rec.id
)
select title into columntitle from hr.columns where id = rec.id;
dbms_output.put_line(columntitle);
end loop;
end;
end loop ;close c1; end;
ORA-06550: line 11, column 6:
PLS-00103: Encountered the symbol "CREATE" when expecting one of the following:
( begin case declare end exit for goto if loop mod null
pragma raise return select update while with
<<
continue close current delete fetch lock insert open rollback
savepoint set sql execute commit forall merge pipe purge
06550. 00000 - "line %s, column %s:\n%s"
*Cause: Usually a PL/SQL compilation error.
*Action :
Bind Variable "new" is NOT DECLARED
anonymous block completed
Bind Variable "new" is NOT DECLARED
anonymous block completed
Thanks
A trigger is a standalone separate piece of code that is usually considered DDL, the language that defines metadata for objects.
You cannot have a trigger declaration embedded inside a PL/SQL block. IF you need to CREATE some PL/SQL code on the fly - not a great idea - consider the DMBS_DDL.CREATE_WRAPPED procedure. You seem to have EXECUTE IMMEDIATE in mind as well. If so, have a read on this: (http://docs.oracle.com/cd/B19306_01/appdev.102/b14258/d_ddl.htm)
You should define your trigger BEFORE running your PL/SQL in other words. Make two scripts.

Oracle SQL Stored Procedure Cursor print

Ok so I am working on a homework assignment using stored procedures.
Essentially i am just trying to use a stored procedure to run a query then print the results.
Here is what i have so far.
create or replace procedure movie_actors (mtitle varchars)as
DECLARE
CURSOR c1 is SELECT "NAME",GENDER,ADDRESS FROM MOVIESTAR WHERE "NAME" in(
SELECT STARNAME FROM STARSIN WHERE MOVIETITLE=mtitle);
actor_name MOVIESTAR.NAME%TYPE;
actor_gender MOVIESTAR.NAME%TYPE;
actor_address MOVIESTAR.ADDRESS%TYPE;
BEGIN
LOOP
FETCH c1 INTO actor_name;
FETCH c1 INTO actor_gender;
FETCH c1 INTO actor_address;
EXIT WHEN c1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(mtitle ||', '||actor_name||': '||actor_gender||', '||actor_address);
END LOOP;
END;
I am new to databases and stored procedures. I am not sure if i am really going about this the best way.
It should be pretty simple, I am not sure what I am doing wrong.
This is the compiler error i am getting.
Error(2,1): PLS-00103: Encountered the symbol "DECLARE" when expecting one of the
following: begin function pragma procedure subtype type <an identifier> <a
double-quoted delimited-identifier> current cursor delete exists prior external
language The symbol "begin" was substituted for "DECLARE" to continue.
Error(16,4): PLS-00103: Encountered the symbol "end-of-file" when expecting one of the
following: ( begin case declare end exception exit for goto if loop mod
null pragma raise return select update while with <an identifier> <a double-quoted
delimited-identifier> <a bind variable> << continue close current delete fetch lock
insert open rollback savepoint set sql execute commit forall merge pipe purge
Any help would be greatly appreciated.
First, you have an invalid type:
create or replace procedure movie_actors (mtitle varchars)as
^
This should be varchar2, not varchars.
Second, you don't need the DECLARE here. The "as" kinda substitutes for it. Start your proc like this:
create or replace procedure movie_actors (mtitle varchar2)as
CURSOR c1
Finally, I strongly recommend changing this:
CURSOR c1 is SELECT "NAME",GENDER,ADDRESS FROM MOVIESTAR WHERE "NAME"
... to this (no double quotes):
CURSOR c1 is SELECT NAME,GENDER,ADDRESS FROM MOVIESTAR WHERE NAME
The double quotes will make the column name case sensitive. You're lucky in this case because the default in Oracle is uppercase, but sooner or later using double quotes like this will cause you trouble - there are plenty of StackOverflow postings from frustrated users who've lost hours or time from using double quotes when they didn't have to.

Oracle SQL Problems using Variables

Having some simple issues here but I've been up for so many hours having trouble focusing so hoping someone else with a fresh head can answer this easy question which I can't seem to find a good answer that works for me in SQL Developer
DECLARE
TEST123 NUMBER;
BEGIN
SELECT COUNT(APP_ID) INTO TEST123 FROM applicant_credit;
SELECT * FROM APPLICANT_CREDIT;
END;
When I run this which seems easy enough to me I am getting error:
Error report:
ORA-06550: line 5, column 3:
PLS-00428: an INTO clause is expected in this SELECT statement
06550. 00000 - "line %s, column %s:\n%s"
*Cause: Usually a PL/SQL compilation error.
Also I have a stored procedure I made and works when I send it hard coded numbers, but I need to pass it the count of records from the applicant_credit mentioned in the earlier query which is what I'm actually after. Would the execute stored procedure work the same in the above block as it does outside a block. So should this work??
DECLARE
TEST123 NUMBER;
BEGIN
SELECT COUNT(APP_ID) INTO TEST123 FROM applicant_credit;
EXECUTE UPDATE_DECISION(102, 1, 1, 1, 1, TEST123);
SELECT * FROM APPLICANT_CREDIT;
END;
When I run this I get:
Error report:
ORA-06550: line 5, column 11:
PLS-00103: Encountered the symbol "UPDATE_DECISION" when expecting one of the following:
:= . ( # % ; immediate
The symbol ":=" was substituted for "UPDATE_DECISION" to continue.
Hitting the wall a bit here, any help is appreciated!!
for the first sql statement, you are getting that error because you cannot execute a select * statement inside a plsql block in that way. You can either use a cursor or a bulk collect statement or any other way to "redirect" the output of select * into a collection of records.
DECLARE
TEST123 NUMBER;
cursor c_cur
is select col_1, col_2 from application_credit;
BEGIN
SELECT COUNT(APP_ID) INTO TEST123 FROM applicant_credit;
-- loop through the cursor if required
END;
your second sql statement gave an error because you cannot use an execute statement inside the plsql block (unless it is execute immediate which is completely different). So, you can modify the code as follows :-
DECLARE
TEST123 NUMBER;
cursor c_cur is
select col1, col2 from applicant_credit;
BEGIN
SELECT COUNT(APP_ID) INTO TEST123 FROM applicant_credit;
UPDATE_DECISION(102, 1, 1, 1, 1, TEST123);
-- loop through the cursor if required
END;
some helpful links :-
http://www.techonthenet.com/oracle/cursors/declare.php
http://www.oracle.com/technetwork/issue-archive/2008/08-mar/o28plsql-095155.html
You do not need PL/SQL at all for this unless you are trying to learn it. All can be done with SQL only.
DECLARE
TEST123 NUMBER:= 0;
BEGIN
UPDATE_DECISION(102, 1, 1, 1, 1, TEST123);
-- The outer query is not required, this is only to show you the correct syntax.
SELECT * INTO TEST123 -- you are selecting from applicant_credit
FROM
(
SELECT COUNT(app_id) FROM applicant_credit
);
END;
/