PL/SQL Using SQL%NOTFOUND to raise a user defined exception in a function
I have written the following function for finding the number of items in stock in the item table.
CREATE OR REPLACE function getAmount (ItemID IN NUMBER)
RETURN NUMBER
AS
invalid_id EXCEPTION;
returnedQty number;
BEGIN
Select qty
Into returnedQty
From item
Where itemNo = ItemID;
RETURN (returnedQty);
IF SQL%NOTFOUND THEN
RAISE invalid_id;
END IF;
COMMIT;
Exception
WHEN invalid_id THEN
DBMS_OUTPUT.PUT_LINE('Invalid ID entered');
END getAmount;
The function compiles successfully, although there is a problem that Oracle is not handling my user-defined exception invalid_id
If I use the following for a valid itemID:
DECLARE
return_value number;
BEGIN
return_value := getAmount(1);
DBMS_OUTPUT.PUT_LINE (return_value);
END;
then the function returns the quantity of items in stock correctly.
However, if I enter an incorrect itemID, say 20
DECLARE
return_value number;
BEGIN
return_value := getAmount(20);
DBMS_OUTPUT.PUT_LINE (return_value);
END;
The invalid_id exception is not raised, and the Oracle errors says: no_data_found and the function has not returned a value. If I add a no_data_found exception, this works perfectly, but for this assignment I must write my own user-defined error.
Any help would be very much appreciated!
Thank you.
What you're trying to do, is to use an implicit cursor. Implicit cursors will raise no_data_found and too_many_rows in case of an error. Explicit cursors will not.
Also, you have a small coding error ... a little rewrite and your code will do as you want to:
CREATE OR REPLACE function getAmount (ItemID IN NUMBER)
RETURN NUMBER
AS
invalid_id EXCEPTION;
returnedQty number;
cursor citem is
Select qty
From item
Where itemNo = ItemID;
fnd boolean;
BEGIN
open citem;
fetch citem Into returnedQty;
fnd := citem%found;
close citem;
if fnd then
RETURN (returnedQty);
else
RAISE invalid_id;
END IF;
/* Do not catch your own exception or the calling code will not receive it.
Exception
WHEN invalid_id THEN
DBMS_OUTPUT.PUT_LINE('Invalid ID entered');
END getAmount;
Your problem is, you're not using a package. This means, that the calling code has no way of catching this user-defined exeption. The correct way is to define a package, define the userdefined exception in the package and refer to it in your code:
create or replace package amt
is
invalid_id EXCEPTION;
function getAmount (ItemID IN NUMBER)
RETURN NUMBER;
end;
create or replace package body amt
is
function getAmount (ItemID IN NUMBER)
RETURN NUMBER
AS
returnedQty number;
cursor citem is
Select qty
From item
Where itemNo = ItemID;
fnd boolean;
BEGIN
open citem;
fetch citem Into returnedQty;
fnd := citem%found;
close citem;
if fnd then
RETURN (returnedQty);
else
RAISE invalid_id;
END IF;
end;
end; -- end package
To do a simple test, you'll do:
declare
a number;
begin
a := amt.getAmount(123);
dbms_output.put_line('The result is '||a);
exception
when amt.invalid_id then
dbms_output.put_line('ID not found');
end;
Other ways is to raise the exception in your no_data_found block.
But I'm REALLY puzzled if there's really someone out there who prefers a user-defined exception instead of the clearly defined NO_DATA_FOUND exception.
I can't be sure of course, but are you sure what they mean is they don't want ANY exception? That's a pretty common requirement.
In general - explicit cursors are a bit faster because Oracle does not have to do a second fetch to determine TOO_MANY_ROWS. And it's not too much additional writing. Explicit cursors will never raise exceptions - unless you use dynamic sql and your SQL is invalid.
Good luck
Similar Messages
-
How to raise the user defined Exceptions in XI ?
Hi All
I am learning XI ...i want know how to set up the user defined Exceptions
in XI?
Where and What are the settings need to be done ?
Same time where can check the LOG file ? to see all the server information ?
Welcome to your answers
Regards
RakeshRakesh,
Check this weblogs which will guide you:
/people/bhavesh.kantilal/blog/2006/07/25/triggering-xi-alerts-from-a-user-defined-function
/people/alessandro.guarneri/blog/2006/01/26/throwing-smart-exceptions-in-xi-graphical-mapping
/people/stefan.grube/blog/2005/12/30/test-user-defined-functions-for-the-xi-graphical-mapping-tool-in-developer-studio
Also check this thread:
Mapping test throughs exception for UDF that does'nt exist anymore
---Satish -
In which of the following sections of a PL/SQL block is a user-defined exception raised?
Hi,
A (somewhat elementary) question:
In which of the following sections of a PL/SQL block is a user-defined exception raised?
a) Exception section
b) Declarative section
c) Error handling section
d) Executable section
I'd be interested to hear people's answers.
Thanks.As Etbin already noted, there are only 3 sections and user-defined exception can be raised in any of them. User-defined exception raised in declarative section example:
declare
year_zero exception;
pragma exception_init(year_zero,-01841);
begin
declare
v_dt date := to_date(1721420,'j');
begin
null;
end;
exception
when year_zero
then
dbms_output.put_line('Year 0!');
end;
Year 0!
PL/SQL procedure successfully completed.
SQL>
User-defined exception raised in executable section example:
declare
year_zero exception;
pragma exception_init(year_zero,-01841);
v_dt date;
begin
v_dt := to_date(1721420,'j');
exception
when year_zero
then
dbms_output.put_line('Year 0!');
end;
Year 0!
PL/SQL procedure successfully completed.
SQL>
User-defined exception raised in exception handling section example:
declare
year_zero exception;
pragma exception_init(year_zero,-01841);
v_dt date;
begin
declare
v_num number;
begin
v_num := 1 / 0;
exception
when others
then
v_dt := to_date(1721420,'j');
end;
exception
when year_zero
then
dbms_output.put_line('Year 0!');
end;
Year 0!
PL/SQL procedure successfully completed.
SQL>
SY. -
Error : ORA-06510: PL/SQL: unhandled user-defined exception
Hi,
Please help on this Error.
Here is my code for Trigger
Code for Trigger
CREATE OR REPLACE TRIGGER TRG_EXCEP AFTER INSERT ON TEST FOR EACH ROW
DECLARE
vInt NUMBER := 0;
vErr EXCEPTION;
BEGIN
vInt := :OLD.TEST_ID;
IF vInt > 10 THEN
INSERT INTO TEST1 VALUES (:NEW.TEST_ID,:NEW.TEST_NAME);
ELSE
RAISE vErr;
END IF;
EXCEPTION
WHEN vErr THEN
INSERT INTO TEST1 VALUES (0,:NEW.TEST_NAME);
END;
While inserting in to the table TEST iam getting the following error
Error on line 0
INSERT INTO TEST VALUES (147541,'Mm',SYSDATE)
ORA-00001: unique constraint (DB_TEST.SYS_C005327) violated
ORA-06512: at "DB_TEST.TRG_EXCEP", line 13
ORA-06510: PL/SQL: unhandled user-defined exception
Someone help me please ...............
Thanks,
Murali.VHi,
I made the mistake here
INSERT INTO TEST1(id,name) VALUES (0,:NEW.TEST_NAME);
where i defined the id as primary key.
But the another problem for me now is while compiling the trigger after i modified,
i get this error
11:37:05 Error: TRIGGER DB_TEST.TRG_EXCEP
On line: 7
PLS-00553: character set name is not recognized
Please help.
Thanks,
Murali.V -
How to use user defined exception class
Hi all
I just need som help with creating a user defined exception class.
Im writing a small/simple text editor.
My exception class looks like this:
public class myExcp extends Throwable
private String message;
public myExcep(String message)
this.message = message;
public void display()
System.out.println(message);
I would like to use it when a user tries to open a exe-file instead of a txt file.
Here is some code from the editor:
if (e.getSource() == open)
saveOld();
if (fc.showOpenDialog(null)== JFileChooser.APPROVE_OPTION)
readFile(fc.getSelectedFile().getAbsolutePath());
saveas.setEnabled(true);
So, should I use exception here or at the readFile method?
readfile:
private void readFile(String fileName)
try
String tmp = fileName.substring(fileName.length() -4, fileName.length());
if (!tmp.equals(".exe"))
FileReader r = new FileReader(fileName);
textarea.read(r, null);
r.close();
currentFile = fileName;
label.setText(currentFile);
changed = false;
catch (IOException e)
JOptionPane.showMessageDialog (this, "Cannot find the file " + fileName);
Where and how do I use my exception class.
Do I need to create an instance? Where?
Should the exception class extend Exception instead?
Thank you in advance /Extend Exception, not Throwable. It's a checked exception that way.
Follow the Sun coding standards and make that exception class name start with a capital letter.
When you extend Exception, override all four ctors.
What's that display method you added? Isn't getMessage() good enough?
You need to create a new instance just before you throw the exception, of course.
Sounds like a terrible design, by the way. Exceptions shouldn't be used like "go to" for app logic. They should signal unrecoverable conditions. You can easily recover from the situation you've described simply by displaying a pop-up that tells the user to open only text-readable file types. I think that's a better solution.
% -
Raising USER DEFINED exceptions
Can I raise my own exception for a Select clause(rather than the
default no_data_found exception?)
Lets suppose I have a Select query which does not return a row.
Rather than go to the no_data_found exception,I'd like to create
my own exception
Select sdi_num into v_sdi_num
from sdi
where sdi_num = 0; -- row returns no data.
EXCEPTION
When
no_data_found
then
...........Now,I want to raise my own exception for this Select clause that does not return a row,rather than
the default no_data_found exception.
Some thing like the below:
Select sdi_num into v_sdi_num
from sdi
where sdi_num = 0; -- row returns no data.
If v_sdi_num IS NULL THEN
RAISE my_own_exception;
END IF;How do I raise my own exceptions in place of no_data_found?Typically you would handle the NO_DATA_FOUND at the point it is raised by using a nested BEGIN .. END; block and raise your own exception instead.
Personal Oracle Database 10g Release 10.1.0.2.0 - Production
With the Partitioning, OLAP and Data Mining options
SQL> CREATE TABLE sdi (sdi_num NUMBER);
Table created.
SQL> SET SERVEROUTPUT ON;
SQL> DECLARE
2 v_sdi_num sdi.sdi_num%TYPE;
3 no_sdi_num_found EXCEPTION;
4 BEGIN
5
6 BEGIN
7 SELECT sdi_num
8 INTO v_sdi_num
9 FROM sdi
10 WHERE sdi_num = 0; -- row returns no data.
11 EXCEPTION
12 WHEN NO_DATA_FOUND THEN
13 RAISE no_sdi_num_found;
14 END;
15
16 EXCEPTION
17 WHEN no_sdi_num_found THEN
18 DBMS_OUTPUT.PUT_LINE ('sdi number not found.');
19
20 END;
21 /
sdi number not found.
PL/SQL procedure successfully completed.
SQL> -
Using decode in where clause with user defined function
Hi,
I have a below query which is failing as the function in the decode taking all cust_account_id as input parameter instead of the one which satisfies the condition in the inner query.So please provide a solution how can i pass only the selected one.
SELECT hca.cust_account_id
FROM hz_cust_accounts hca
WHERE hca.org_id=FND_PROFILE.value('ORG_ID')
AND hca.cust_account_id = (SELECT DISTINCT hcasa.cust_account_id
FROM hz_cust_acct_sites_all hcasa
WHERE hcasa.cust_account_id =hca.cust_account_id
AND hca.org_id = hcasa.org_id)
AND DECODE (hca.status , 'A', xx_ar_cust_audit_pkg.get_ship_to_order_type(hca.cust_account_id)) IS NOT NULL
Thanks,
AbhilashI'm having to guess without access to your tables, but I think changing the IN to a join should produce the same results. The JOIN should be evaluated before applying the WHERE clause, so this may resolve your problem.
SELECT hca.cust_account_id
FROM hz_cust_accounts hca
INNER JOIN hz_cust_acct_sites_all hcasa
ON hcasa.cust_account_id = hca.cust_account_id
AND hca.org_id = hcasa.org_id
WHERE hca.org_id = FND_PROFILE.value('ORG_ID')
AND DECODE (hca.status , 'A', xx_ar_cust_audit_pkg.get_ship_to_order_type(hca.cust_account_id)) IS NOT NULLAlternately, you could next part of the query and break the DECODE into the parent so it is evaluated after the inner query. This is likely uglier from a performance standpoint, though:
SELECT cust_account_id
FROM
SELECT hca.cust_account_id, hca.status
FROM hz_cust_accounts hca
WHERE hca.org_id=FND_PROFILE.value('ORG_ID')
AND hca.cust_account_id = (SELECT DISTINCT hcasa.cust_account_id
FROM hz_cust_acct_sites_all hcasa
WHERE hcasa.cust_account_id =hca.cust_account_id
AND hca.org_id = hcasa.org_id)
WHERE DECODE (status , 'A', xx_ar_cust_audit_pkg.get_ship_to_order_type(cust_account_id)) IS NOT NULL; -
Regardin handling exception in a function, while using that function in sql
Hi gurus,
I have a question regarding logging exceptions while using functions.
I wrote a separate package to handle errors, where i have a procedure.
In this proc i'm logging my error into a table and then raise the error to the front end.
Ex:
proc_log_and_raise -- this proc... inserts my error into a table and then raisenow i included this error procedure in all functions and procedures.
consider an example with a sample procedure and function.
function func_1(( v_var varchar2) return varchar2 is
begin
select column2
from table2
where col1 = v_var;
exception
when others then
proc_log_and_raise;
end;
procedure proc_1( v_var varchar2) is
begin
select func_1(v_var) -- error occurs here..
from table_a
where col1 = v_var;
exception
when others then
proc_log_and_raise;
end; now i do
exec proc_1( v_var );but now my problem is, when an error occurs in func_1, i'm getting an error with DML operation ( as we are inserting into error table)
ORA-14551: cannot perform a DML operation inside a query.
so what i want to do is, log both function and procedure where error occured.
So is there any other better way, we can write our exception handling, so that i can log error and use function in a select statement.
thank you.I changed my procedure a little, to make it simple.
FUNCTION PKG_WEEKLY.FUNC_1
RETURN NUMBER IS
exc exception;
BEGIN
raise exc;
RETURN v_provr_rcoupt;
EXCEPTION
when exc then
PKG.PKG_ERROR.USP_LOG_AND_RAISE(
'batch_1',
'func_1',
SQLCODE,
DBMS_UTILITY.FORMAT_ERROR_STACK || DBMS_UTILITY.FORMAT_ERROR_BACKTRACE());
END FUNC_1;
PROCEDURE PKG_WEEKLY.PROC_1(
cur_details OUT sys_refcursor) IS
BEGIN
OPEN cur_details FOR
SELECT NVL(PKG.PKG_WEEKLY.FUNC_1,0)) FROM DUAL;
EXCEPTION
WHEN OTHERS THEN
REPORT_APP_PKG.PKG_REPORT_ERROR.USP_LOG_AND_RAISE(
'batch_1',
'PROC_1',
SQLCODE,
DBMS_UTILITY.FORMAT_ERROR_STACK || DBMS_UTILITY.FORMAT_ERROR_BACKTRACE());
END PROC_1; Now i execute it.
exec PKG_WEEKLY.PROC_1(:cursor); Error logged into the table:
242 batch_1 func_1 ORA-06510: PL/SQL: unhandled user-defined exception
ORA-06512: at "REPORT_APP_PKG.PKG_REPORT_WEEKLY_CAO", line 230
04/14/2009 16:09:25
ERRORS displayed to the front end:
ORA-20156: ORA-06510: PL/SQL: unhandled user-defined exception
ORA-06512: at "PKG.PKG_WEEKLY", line 230
ORA-06512: at "PKG.PKG_ERROR", line 48
ORA-06512: at "PKG.PKG_ERROR", line 226
ORA-06512: at "PKG.PKG_WEEKLY", line 261
thank you -
Report Retrieval Times in BPCv7 SP3 using SQL 2008
General Information: We are a two server environment, one WEB and one SQL, using SQL 2008. We are using BPC v7 SP3. In our devlopment environment, we have selected a handful of reports to use as a benchmark against our production version of Outlooksoft version 4.
Problem: The benchmark reports are taking longer to retrieve in BPC v7 then they are in Outlooksoft version 4 SP9. We have stripped out the dimension formulas, unchecked the INAPP for each dimension property, reset the compatability level in SQL, and removed all data from the facttables in BPC version 7. The initial pull of the report seems to take almost 3 times as long in BPC v7 than in Outlooksoft version 4. Subsequent pulls, changing the date, take less than 15 seconds for the same report.
We are at a stand still trying to figure out why we are experiencing such lengthy retrieval times in the initial pull of a report in BPC version 7.
Additional Info: In our development environment of BPC v7, we currently have only 4 users set up to test. Our Outlooksoft version 4 has a total of 186 users. I don't know the maximium concurrent users we may have at one time.
Question: We are wondering if any other users are experiencing the same issue when they try and retrieve data from a report in BPC version 7? Please share your insight to this problem.Hi Irene,
It is a big diference of design between 4.x and 7.x.
Into 4.x when you pull data into a report actually you are using PTS from client and you already have the connection and everything from client direct to OLAP server.
In 7.x all the request are going first to application server and the application server is the one taking the data from OLAP and after that data is sent to client.
So first time when you are doing refresh of report into application server it is necessary to create instances for all COM+ components necessary connection etc...and in that case the reports is taking longer.
When you are doing other refresh with the same reports or with other the time for refresh is much faster because already the COM+ instances were created and in this case the reports should be faster than v 4.x
So I suggest to try the follow test.
after login with BPC client just open first a small reports which you know is not taking too long.
After that open your big report. It should retrieve data faster than 4.x or almost the same time.
Also make sure you have all the settings done from Tunning Guide for BPC 5.x ( these settings can be applied also for 7.X)
to be sure that your 7.0 environment is working properly. This tunning guide can be found into bpx/sdn HTG section.
I hope this will help.
Regards
Sorin Radulescu -
Using bind variables in user defined reports
How do I go about using a bind variable in a user defined report?
Here's a trivial example in SQL*Plus:
var ublocksize number
begin
select value into :ublocksize
from v$parameter
where name = 'db_block_size';
end;
select :ublocksize from dual;
This code does not work in raptor.
The error displayed is:
Missing IN or OUT parameter at index:: 1
Vendor code 17041
any ideas?You also have a second issue of supporting the following syntax in SQL scripts:
var ublocksize number
begin
select value into :ublocksize
from v$parameter
where name = 'db_block_size';
end;
We are itterating to support all SQL plus commands
Mike -
How to use negation in user defined rules?
Hi,
Can you please show me an example to use negation in user defined rule? I created a rule like below (the rule says if a patient has a fever problem and not have penicillin hypersensitivity, then recommend medication1):
INSERT INTO mdsys.semr_myMedicineRB VALUES('rule1',
'(?p rdf:type :Patient) (?p :present ?c1) (?c1 rdf:type :Fever) (?c2 rdf:type :Penicillin_Hypersensitivity)',
'(NOT_EXISTS(p :present c2))',
'(?p :recommendation :medication1)',
SEM_ALIASES(SEM_ALIAS('','http://www.example/medicine#')));
The rule successfully inserted into the rulebase. However, I cannot pass the entailment creation phase and got the errors:
ORA-29532: Java call terminated by uncaught Java exception: java.sql.SQLException: Missing IN or OUT parameter at index:: 1
ORA-06512: at "MDSYS.SDO_SEM_INF_INTERNAL", line 16453
ORA-06512: at "MDSYS.SDO_SEM_INFERENCE", line 302
ORA-06512: at "MDSYS.SDO_SEM_INFERENCE", line 352
ORA-06512: at "MDSYS.RDF_APIS", line 118
ORA-06512: at line 2
29532. 00000 - "Java call terminated by uncaught Java exception: %s"
*Cause: A Java exception or error was signaled and could not be
resolved by the Java code.
*Action: Modify Java code, if this behavior is not intended.
According to the post built-in primitives(noValue,remove) for user defined rules, it seems negation is not supported in user defined rules. Can you please advice how to implement negation in user defined rules? Thanks a lot in advance.
HongHi Hong,
Let's look at this similar but simplified problem:
if (?p rdf:type :Patient) and (NOT_EXISTS(?p :present :c2)) ==> (?p :recommendation :medication1)
You can use something like this in the user defined inferencing:
-- First get the numeric IDs for the relevant URIs
recomID := sdo_sem_inference.oracle_orardf_add_res('http://..../recommendation');
medID := sdo_sem_inference.oracle_orardf_add_res('http://..../medication1')
rdfTypeID := sdo_sem_inference.oracle_orardf_res2vid('... full URI for rdf:type');
patientID := ...
presentID := ...
c2ID := ...
-- Now this query will find out ?p that satisfy (?p rdf:type :Patient) but not
-- (?p :present :c2)
sqlStmt := '
select ids1.sid sub
from ' || src_tab_view || ' ids1
where ids1.pid= ' || to_char(rdfTypeID,'TM9') || '
and not exists (
select 1
from ' || src_tab_view || '
where sid = ids1.sid
and pid = ' || to_char(presentID, 'TM9') || '
and oid = '|| to_char(c2ID,'TM9') || '
insertStmt := '
insert /*+ parallel append */
into ' || output_tab || '(sid, pid, oid)
select sub, '||to_char(recomID,'TM9') || ',' || to_char(medID,'TM9') || '
from (' || sqlStmt || ')'
More details can be found in
http://docs.oracle.com/cd/E16655_01/appdev.121/e17895/inference_extension.htm#CHDDBGEC
Hope it helps,
Zhe Wu -
Update User Defined Field using DBDataSource
Hi All,
I'm trying to update the user defined field using the DBDataSource object. However an error occurred - "Item is not a User-Defined Field".
The code used is as follows:
Dim oDS as SAPbouiCOM.DBDataSource
Dim oForm as SAPbouiCOM.Form
Set oForm = SBO_Application.Forms.GetForm("139", 1)
Set oDS = oForm.DataSources.DBDataSources.Item("ORDR")
oDS.SetValue("U_Field1",oDS.Offset,"abc")
Please help.If you haven´t put the field directly in the standard form the user defined fields are in a different form. This form has the same type but with "-" before it.
So so should use this code to get the user defined fields form:
Set oForm = SBO_Application.Forms.GetForm("-139", 1)
Maybe this can be the cause -
Sequence Quiz Using User Defined Variables - Can See Underlying Variable Name On Move
I have just tested using 1 slide to capture several user defined variables and the next slide to insert those variables as options in a sequence quiz slide.
This works but as soon as I grab an object to begin sequencing them the underlying variable name shows up alongside the variable content.
Am wondering if I am attempting something that shouldn't be possible in Captivate and / or if there is a fix?
ThanksSure, I'm using Captivate 8. On a test project I've created:
a slide with 2 text entry boxes, their contents are stored in variables
another slide with a sequence question (using the native captivate question slide)
The labels on the 2 sliders on the question slide use the variables from the previous slide.
This works, so if the variables are as follows:
$$data_sequence1$$ - "blah blah blah"
$$data_sequence2$$ - "blah"
The labels on the sliders on the sequence question will be "blah blah blah" and "blah". as intended.
The issue is when I click one of the sliders to drag it to sequence the variable name will flash up on screen. So if I touch the slider with the label "blah blah blah" $$data_sequence1$$ will flash up on screen.
I have other slides on there but these are the two related to this question. I haven't fully published the project I've previewed it. -
Internal table value checking in custom table using SQL...
I have a table which has following fields:
X1 TABLE (ZCONfig custom table)
LIFNR land1
123 br
234 br
456 br
567 Gr
and
X2 TABLE: (Internal table)
LIFNR:
234
567
123
Now I want to see if all the field values of LIFNR in internal table X2 (X2-LIFNR) are present in X1 or not.
Raise error if it is not.
How do I do this using SQL ? I guess I have to use read statement.
Please help. Points will be awarded.
Thanks.
RegardsHi Tushar,
1 Ya u are right , we need to use READ statement.
2. Populate X1 (all records)
in an internal table.
3. Then Loop at X2
and compare with X1.
( u can also keep an extra field in X2
of type c, so that if a record is found,
mark it as X )
4. try this code (just copy paste)
REPORT abc.
DATA : BEGIN OF itab OCCURS 0,
bukrs LIKE t001-bukrs,
present TYPE c,
END OF itab.
DATA : t001 LIKE TABLE OF t001 WITH HEADER LINE.
itab-bukrs = '1000'.
APPEND itab.
itab-bukrs = 'X000'.
APPEND itab.
SELECT * FROM t001 INTO TABLE t001.
LOOP AT itab.
READ TABLE t001 with key bukrs = itab-bukrs.
IF sy-subrc = 0.
itab-present = 'X'.
MODIFY itab.
ENDIF.
ENDLOOP.
BREAK-POINT.
regards,
amit m.
Message was edited by: Amit Mittal -
Count rows from multiple tables using SQL only
Hi, I know this has probably been answered before, but I couldn't find the answer anywhere. Please help.
I'd like count(*) [rows] for all tables in database using SQL only - no PL/SQL
The result should be something like:
Table RowCount
DBA_TABLES 1000
DBA_USERS 50
etc.
Thanks!offcource write this script:
create or replace procedure count_tables (ip_schema VARCHAR2)
is
lv_owner VARCHAR2(100);
lv_table_name VARCHAR2(100);
lv_sql_statement VARCHAR2(2000);
lv_count_table NUMBER;
CURSOR c1 IS
SELECT owner, table_name
FROM all_tables
WHERE owner = ip_schema
ORDER BY table_name;
begin
dbms_output.put_line ('+--------------------------------------------------------------------+');
dbms_output.put_line ('¦ | | ¦');
dbms_output.put_line ('¦ Schema Name | Table Name | Number of Rows ¦');
dbms_output.put_line ('¦ | | ¦');
dbms_output.put_line ('¦------------------------------------------------------------------¦');
OPEN c1;
LOOP
FETCH c1 INTO lv_owner , lv_table_name;
EXIT WHEN c1%NOTFOUND;
lv_sql_statement := 'SELECT count(*) FROM ' || lv_owner || '.' || lv_table_name;
EXECUTE IMMEDIATE lv_sql_statement INTO lv_count_table;
IF lv_count_table > 0 THEN
dbms_output.put_line ('| '||rpad(lv_owner, 14, ' ')||'| '|| rpad(lv_table_name, 32, ' ')||'| '|| rpad(lv_count_table, 16, ' ')||' |');
-- dbms_output.put_line ('|---------------|---------------------------------|------------------|');
END IF;
END LOOP;
CLOSE c1;
dbms_output.put_line ('+--------------------------------------------------------------------+');
exception
WHEN OTHERS THEN
dbms_output.put_line ('owner: '||lv_owner||' - table: '||lv_table_name||' - '||sqlerrm);
end count_tables;
set serveroutput on size 1000000
exec count_tables
drop procedure count_tables;
Maybe you are looking for
-
Since I've installed Mountain Lion, I am having lock up issues with multiple programs. MS Outlook has crashed and I've lost all my folders. HELP?
-
Problem installing cs6 Flash.
I successfully installed cs6 design web premium except for Flash Pro. Message said there was an installation error. This happened on both my desktop running Snow Leopard and on my MacBook Pro running Lion. How do I go about completing the installatio
-
Balance not carry forward with t-code F.16
Hi I have carry forward GL balances with t-code F.16 but system not display in FGI3 t-code. Please let me know what I will do. Thanks & Regards, Hemant Kumar Maurya
-
Hi everybody, i started to program in JSP only from yesterday and i'd like to execute a statement SQL from my JSP page.... My code is <%Class.forName("oracle.jdbc.driver.OracleDriver");%> <%java.sql.Connection c = java.sql.DriverManager.getConnection
-
is anyone else expierencing apple mail mixing up the mail when you do a search im trying to find an email from apple support but the headers and main mail body dont match which makes this impossible Any solutions out there?