IN my oracle database i want to create a function or procedure with cursor which will use dynamic table name.here is my code.
CREATE OR REPLACE Function Findposition ( model_in IN varchar2,model_id IN number) RETURN number IS cnumber number;
TYPE c1 IS REF CURSOR;
c2 c1;
BEGIN
open c2 FOR 'SELECT id,ROW_NUMBER() OVER ( ORDER BY id) AS rownumber FROM '||model_in;
FOR employee_rec in c2
LOOP
IF employee_rec.id=model_id then
cnumber :=employee_rec.rownumber;
end if;
END LOOP;
close c2;
RETURN cnumber;
END;
help me to solve this problem.IN
c1type for a weakly typed ref cursor. You can just use theSYS_REFCURSORtype.OPENa cursor, you have toFETCHfrom it in a loop and you have toCLOSEit. You can’tOPENandCLOSEit but then fetch from it in an implicit cursor loop.FETCHinto those variables.ROWIDis a reserved word so I usedROWPOSinstead.Putting that together, you can write something like
I believe this returns the result you expect
Note that from an efficiency standpoint, you’d be much better off writing this as a single SQL statement rather than opening a cursor and fetching every row from the table every time. If you are determined to use a cursor, you’d want to exit the cursor when you’ve found the row you’re interested in rather than continuing to fetch every row from the table.
From a code clarity standpoint, many of your variable names and data types seem rather odd. Your parameter names seem poorly chosen– I would not expect
model_into be the name of the input table, for example. Declaring a cursor namedc2is also problematic since it is very non-descriptive.