Stored procedure and function - return table type
Hello again :)
I have one simple question :) Maybe on this forum the question was asked, but I found only similar question and they didn't help me.
It's possible return in Stored Function (with StoredProcedureFunction) as result return TABLE type? Or return table type with output parametr with Stored Procedure? Or instead of the table return the db object, but it is similar problem:)
Now, I can using db types TABLES or DB OBJECTS as INPUT parameters with call stored functions or procedures, for example:
I have this simple db object:
create or replace type BUFFER_DATA_R as object( detail VARCHAR2(4000 ))
And this simple table:
CREATE OR REPLACE TYPE BUFFER_DATA_T IS TABLE OF BUFFER_DATA_R
I create simple domain class object:
*public class DMBufferDataStruct {*
public String bufferData;
And I mapped in java with ObjectRelationalDataTypeDescriptor:
ObjectRelationalDataTypeDescriptor descriptor = new ObjectRelationalDataTypeDescriptor();
descriptor.setJavaClass(DMBufferDataStruct.class);
descriptor.setTableName("BUFFER_DATA_T");
descriptor.setStructureName("BUFFER_DATA_R");
descriptor.setPrimaryKeyFieldName("DETAIL");
descriptor.addFieldOrdering("DETAIL");
descriptor.addDirectMapping("bufferData", "DETAIL");
and join to server session ...
Well, i using this doimain class object as input parametr wih stored procedure call:
ObjectRelationalDatabaseField ordf = new ObjectRelationalDatabaseField("");
ordf.setSqlType(Types.STRUCT);
spCall.addNamedArgument(key, key,
Types.ARRAY,
"BUFFER_DATA_T",
ordf);
query.addArgument(key);
args.add(paramsInputs.get(key));
in paramsInputs is Vector of DMBufferDataStruct...
Well, this work fine!
But I can not figure, how to return this table from output parameters of stored procedure or as a return value from stored function?
Example of exceptions:
The number of arguments provided to the query for execution does not match the number of arguments in the query definition. - return as output parameter
PLS-00382: expression is of wrong type - used as result from stored function
So, my question is: Is possible return this table type from stored procedure or function? And if YES, how can I set output argument for call?
Thx advance!
Sorry for my English! :)
Best regards, KLD
Your question is: what is faster PL/SQL or PL/SQL? And the answer is: it is PL/SQL of course!
As a general rule, you use a function when you return exactly one result: a number or a string or (more complex) instance of an object type or REF CURSOR or PL/SQL collection.
You use a procedure when:
a) you just do the job and return no result
b) you return multiple results - you can use multiple IN/OUT or OUT parameters
Imagine you have to write a program unit that performs a partitioned table maintenance by adding a partition.
You can implement this unit:
a) if you want return a "status code" (0 on successful completion or non-zero in case of error) then you should use a function
b) if you want no "status code" (in case of error an exception is raised that is handled outside of the program unit) then you should use a procedure
c) if you want "status code", name of tablespace where a partition was created (assume you program is so complex that it can choose different tablespaces based on metadata and free space available) and free space in that tablespace after the creation of a new partition then you should use a procedure with 3 OUT parameters.
But these are good programming practices that can be applied to (almost) any 3rd generation programming language, not only PL/SQL.
Similar Messages
-
Diif between Stored procedure and function
HI
I want all the differences between Stored procedure and function.
Even the basic diff is Procedure does not return any value and Function must be...
Thansk In advance...1) Functions are used for computations where as procedures can be used for performing business logic That's an opinion on usage not an actual difference.
3) You can have DML(insert,update, delete) statements in a function. But, you can not call such a function in a SQL query.Not true. As User defind functons limitations we can use a function that issues DML in a SELECT statement, if it uses the PRAGMA AUTONOMOUS_TRANSACTION.
4) Function parameters are always IN, no OUT is possibleEasily refutable...
SQL> CREATE OR REPLACE FUNCTION my_f (p OUT NUMBER) RETURN DATE
2 AS
3 BEGIN
4 p := to_number(to_char(sysdate, 'DD'));
5 RETURN sysdate;
6 END;
7 /
Function created.
SQL> var x number
SQL> var d varchar2(18)
SQL> exec :d := my_f(:x)
PL/SQL procedure successfully completed.
SQL> print d
D
18-NOV-05
SQL> print x
X
18
SQL>
Stored Procedure :supports deffered name resoultion Example while writing a stored procedure that uses table named tabl1 and tabl2
etc..but actually not exists in database is allowed only in during creationNot sure what this one is about...
SQL> CREATE PROCEDURE my_p AS
2 n NUMBER;
3 BEGIN
4 SELECT count(*) INTO n
5 FROM tab1;
6 END;
7 /
Warning: Procedure created with compilation errors.
SQL> sho err
Errors for PROCEDURE MY_P:
LINE/COL ERROR
4/4 PL/SQL: SQL Statement ignored
5/9 PL/SQL: ORA-00942: table or view does not exist
SQL>
7) A procedure may modifiy an object where a function can only return a value.An ounce of test is worth sixteen tons of assertion...
SQL> CREATE OR REPLACE FUNCTION my_f2 RETURN VARCHAR2
2 AS
3 BEGIN
4 EXECUTE IMMEDIATE 'CREATE TABLE what_ever (col1 number)';
5 RETURN 'OK!';
6 END;
7 /
Function created.
SQL> exec :d := my_f2
PL/SQL procedure successfully completed.
SQL> desc what_ever
Name Null? Type
COL1 NUMBER
SQL> I think there are only two differences between a procedure and a function.
(1) A function must return a value
(2) because of (1) we can use functions in SQL statements.
There are some minor difference in allowable syntax but they are to do withj RETURN values.
Cheers, APC -
How can I get a list of values (one or more) used in the WHERE filter of stored procedures and functions in SQL Server?
How can get a list of values as shown (highlighted) in the sample stored procedure below?
ALTER PROC [dbo].[sp_LoanInfo_Data_Extract] AS
SELECT [LOAN_ACCT].PROD_DT,
[LOAN_ACCT].ACCT_NBR,
[LOAN_NOTE2].OFCR_CD,
[LOAN_NOTE1].CURR_PRIN_BAL_AMT,
[LOAN_NOTE2].BR_NBR,
INTO #Table1
FROM
dbo.[LOAN_NOTE1],
dbo.[LOAN_NOTE2],
dbo.[LOAN_ACCT]
WHERE
[LOAN_ACCT].PROD_DT = [LOAN_NOTE1].PROD_DT
and
[LOAN_ACCT].ACCT_NBR = [LOAN_NOTE1].ACCT_NBR
and
[LOAN_NOTE1].PROD_DT = [LOAN_NOTE2].PROD_DT
and
[LOAN_NOTE1].MSTR_ACCT_NBR = [LOAN_NOTE2].MSTR_ACCT_NBR
and
[LOAN_ACCT].PROD_DT = '2015-03-10'
and
[LOAN_ACCT].ACCT_STAT_CD IN
('A','D')
and
[LOAN_NOTE2].LOAN_STAT_CD IN
('J','Z')
LenfinkelHi LenFinkel,
May I know what is purpose of this requirement, as olaf said,you may parse the T-SQL code (or the execution plan), which is not that easy.
I have noticed that the condition values in your Stored Procedure(SP) are hard coded and among them there is a date values, I believe some day you may have to alter the SP when the date expires. So why not declare 3 parameters of the SP instead hard coding?
For multiple values paramter you can use a
table-valued parameter. Then there's no problem getting the values.
If you could elaborate your purpose, we may help to find better workaround.
Eric Zhang
TechNet Community Support -
How to find stored procedures and functions having SET Ansi_Nulls OFF?
I have query below to find objects with ansi nulls ON. How can i find sql objects with ansi nulls off?
SELECT
SCHEMA_NAME(s.schema_id) + '.' + s.name AS name,
s.create_date,
s.modify_date,
OBJECTPROPERTY(s.object_id,'ExecIsAnsiNullsOn') AS ExecIsAnsiNullsOn
FROM sys.objects s
WHERE
s.type IN ('P','FN')
AND OBJECTPROPERTY(s.object_id,'ExecIsAnsiNullsOn') = 0
ORDER BY SCHEMA_NAME(s.schema_id) + '.' + s.name DESCI think my technet article on this topic will be helpful (check script at the end):
SET
ANSI_PADDING Setting and Its Importance
For every expert, there is an equal and opposite expert. - Becker's Law
My blog
My TechNet articles -
Which is better - SQL Statement in APEX or as a function returning a type?
Hi
I have a general question about best practices for APEX development.
If we have say a report region based on a SQL statement, is it better (from a performance perspective) to have the SQL statement defined in the region in APEX OR have the actual select statement executed in the backend and have the result set returned in a type to APEX?
As an example:
In APEX region
SELECT col1, col2, col3 FROM table_aOR
In APEX region
select col1, col2, col3 from TABLE(CAST(<my package>.<my proceduere > AS <my type >)) ;<my package>.<my proceduere > would obviously execute the statement
SELECT col1, col2, col3 FROM table_ausing dynamic SQL and return the results to APEX in thy type <my type>.
Apologies if this sounds to be a really stupid thing to ask.
Kind regards
PaulDenes Kubicek wrote:
You should use a pipelined function only then when you can't use SQL. Otherwise SQL is the way to go.
Denes Kubicek
http://deneskubicek.blogspot.com/
http://www.opal-consulting.de/training
http://apex.oracle.com/pls/otn/f?p=31517:1
------------------------------------------------------------------------------thanks Denes... but does it matter if:
1. The SQL statement is actually defined in the APEX region
or
2: The select statement is stored in a packageD function and returned to APEX?
I seem to recall an article I read stating that it is best for all client applications to call stored procedures and functions rather than have SQL statement embedded in the actual application?
Kind regards
Paul -
Sort/filter datablock based on procedure that return table type
Hi All,
I’ve got datablock based on procedure that return table type. In the form I have to provide ‘filter and sort records’ functionality. Previously, using tables/views based datablocks, I’ve done that by using:
-- filter
SET_BLOCK_PROPERTY (L_BLOCK_NAME, DEFAULT_WHERE, L_WHERE_CLAUSE);
-- sort
SET_BLOCK_PROPERTY(L_BLOCK_NAME ,ORDER_BY, L_ORDER_BY_CLAUSE);
-- and then
EXECUTE_QUERY;
It doesn’t work with procedure that return table type. How I can do that?
BartekI agree with Andreas, from the sample you have given us, I don't see any reason why you could not merge these queries into a single UNION/UNION ALL query. Also, I would add your summation query to your main query to eliminate this extra step. The result would look something like:
SELECT DISTINCT
pih.id
,d.document_id
,pih.doc_serial_no
,pih.purch_invoice_date
,oh.company_name
,(SELECT NVL(SUM(amount),0)
FROM "YOUR TABLE HERE" yth
WHERE yth."YOUR COLUMN HERE" = pih.id) AS sum_amount
FROM "YOUR TABLES HERE"
WHERE "YOUR JOIN CONDITIONS HERE"
UNION ALL
SELECT DISTINCT
sih.id
,d.document_ind
,sih.doc_serial_no
,sih.sales_invoice_date
,sih.company_name
,(SELECT NVL(SUM(amount),0)
FROM "YOUR TABLE HERE" yth
WHERE yth."YOUR COLUMN HERE" = sih.id) AS sum_amount
FROM "YOUR TABLES HERE"
WHERE "YOUR JOIN CONDITIONS HERE"
[/code]
Hope this helps.
Craig...
+If a response is helpful or correct, please mark it accordingly+
Edited by: CraigB on Feb 23, 2010 1:39 PM
It appears the CODE tags are not working as well as the URL tags. :( -
Stored procedure in package return multiple columns from multiple tables
Hi ,
Can a single stored procedure return multiple column values from different tables.
example:
tabA: col2, tabB:col3,tabC:col4 etc.
one more question:
if a stored procedure like to return 10 columns for a particular record from a single table do i need to define a TYPE statement for each colum like
TYPE col1 is TABLE of varchar
TYPE col2 is TABLE of varchar
here i want to return only one row, not many rows.
thanksYou can try one procedure with OUT or IN/OUT parameters that collect the values from one or more sql statements.
CREATE OR REPLACE PROCEDURE P1
(P_COD IN TABLE.COD%TYPE,
P_DESC1 OUT TABLE1.DESC1%TYPE,
P_DESC2 OUT TABLE2.DESC2%TYPE)
IS
BEGIN
SELECT table1.DESC1, table2.DESC2
INTO P_DESC1, P_DESC2
FROM TABLE1, table2 WHERE
table1.COD = P_COD and
table1.cod = table2.cod ;
END P1;
JP -
Hi Experts,
I have on stored procedure which returns mote than one resultset i want that to store in two different temp table how can achieve this in SQL server.
following is the stored procedure and table that i need to create.
create procedure GetData as begin select * from Empselect * from Deptend
create table #tmp1 (Ddeptid int, deptname varchar(500),Location varchar(100))
Insert into #tmp1 (Ddeptid , deptname ,Location )
exec GetData
create table #tmp (empid int , ename varchar(500),DeptId int , salary int)
Insert into #tmp (empId,ename,deptId,salary)
exec GetData
Niraj SevalkarYou cant get two resultsets out of SP like this. The workaround is to merge and bring the resultsets.
For this number of columns as well as corresponding datatypes have to be compatible. Also you will need one additional column which indicates resultset value. Then use this as filter to get your desired resultset out
create procedure GetData as
begin
select 'resultset1' as Cat,*,.. N columns from Emp
union all
select 'resultset2' as Cat,*,.. N columns from Dept
end
create table #tmp1 (Ddeptid int, deptname varchar(500),Location varchar(100))
Insert into #tmp1 (Ddeptid , deptname ,Location )
Select column1,column2,column3
from OPENROWSET('SQLOLEDB','Data Source=Server_name;Trusted_Connection=yes;
Integrated Security=SSPI','Execute yourdb..GetData')
WHERE Cat = 'resultset1'
create table #tmp (empid int , ename varchar(500),DeptId int , salary int)
Insert into #tmp (empId,ename,deptId,salary)
Select column1,column2,column3, column4
from OPENROWSET('SQLOLEDB','Data Source=Server_name;Trusted_Connection=yes;
Integrated Security=SSPI','Execute yourdb..GetData')
WHERE Cat = 'resultset2'
also see
http://sqlblogcasts.com/blogs/madhivanan/archive/2007/11/26/select-columns-from-exec-procedure-name-is-this-possible.aspx
Another method is to populate table with relevant resultset within procedure itself and then select from the table directly outside.
Please Mark This As Answer if it solved your issue
Please Vote This As Helpful if it helps to solve your issue
Visakh
My Wiki User Page
My MSDN Page
My Personal Blog
My Facebook Page -
Java Stored Procedure via Function Give 0RA 600 from SQL Workshop and App
Hi,
Anyone experienced stored procedures or functions failing when called from APEX app or SQL Workshop ( ora 600 ) yet they work fine when called from SQLPlus?
Sqlplus connected as my apex workspace schema owner:
select net_services.test_db_connection_via_ldap(
'APEXPRD1', 'test1', 'test1', null ) as result from dual;
RESULT
The database connection attempt was SUCCESSFUL
From Apex Sql Worshop:
select net_services.test_db_connection_via_ldap(
'APEXPRD1', 'test1', 'test1', null ) as result from dual;
ORA-00600: internal error code, arguments: [16371], [0x434B08150], [0], [], [], [], [], [], [], [], [], []
NOTE: Same result when run in response to button push on page in application.
Apex Version: 3.2.1.00.10
Oracle Version: 11.1.0.7.0
NOTE: I am using the embedded plsql gateway; was going to try NOT using it to see if it was shared server related (seemed to be from trc files)
Any ideas?
Since the code works from sqlplus, I know that it's good: Here some snippets
-- ========================================================================================
public class NetServices extends Object {
public static String doTestDbConnectionViaLdap
String piDbConnUrl,
String piUserName,
String piUserPassword
String vResult = null;
try
Connection conn = null;
OracleDataSource ods = new OracleDataSource();
ods.setUser( piUserName );
ods.setPassword( piUserPassword );
ods.setURL( piDbConnUrl );
conn = ods.getConnection();
conn.close();
vResult = "The database connection attempt was SUCCESSFUL";
} catch ( SQLException e )
int vErrCode = e.getErrorCode();
String vErrMsg = e.toString();
if ( vErrCode == 1017 ) {
vResult = "The database connection attempt FAILED! Incorrect Username or Password";
} else if ( vErrCode == 17433 ) { // Null Username or Password
vResult = "The database connection attempt FAILED! You must provide both a Username and a Password";
} else if ( vErrCode == 17002 ) {
vResult = "The database connection attempt FAILED! Net Service Name was Not Found";
} else if ( vErrCode == 17067 ) { // NULL Net Service Name
vResult = "The database connection attempt FAILED! You must provide a Net Service Name";
} else {
vResult = "The database connection attempt FAILED! Error " + vErrCode;
return vResult;
} // method: doTestDbConnectionViaLdap
-- ========================================================================================
function do_test_db_connection_via_ldap
pi_db_conn_url IN VARCHAR2,
pi_user_name IN VARCHAR2,
pi_user_password IN VARCHAR2
return VARCHAR2
is -- PRIVATE to the net_services package
language java -- NOTE: See cr_java_class_NetServices.sql for actual java implementation
name 'NetServices.doTestDbConnectionViaLdap
( java.lang.String, java.lang.String, java.lang.String ) return java.lang.String ';
-- ========================================================================================
function test_db_connection_via_ldap
pi_net_service_name IN VARCHAR2,
pi_user_name IN VARCHAR2,
pi_user_password IN VARCHAR2,
pi_search_base IN VARCHAR2
return VARCHAR2
is -- PUBLIC procedure
v_url VARCHAR2(256);
begin
g_err_source := 'NET_SERVICES.test_db_connection_via_ldap';
g_err_action := 'build_jdbc_conn_url_using_oid';
/* NOTE: We don't want to assert the parameters because we don't want to raise
an exception;
-- Get the jdbc connection url that uses oid info
v_url := build_jdbc_conn_url_using_oid( pi_net_service_name, pi_search_base );
return( do_test_db_connection_via_ldap( v_url, pi_user_name, pi_user_password ) );
end test_db_connection_via_ldap;
-- ========================================================================================
Thanks in advance for your consideration.
TroyTroy:
You could be right in your guess that the error is related to MTS. Search Metalink for '16371'. Why not switch your APEX app to use OHS and test whether the error persists. ?
varad -
Oracle procedures returning table type supported in JDBC
We have many procedures who return table type return. The JDBC callable statment does not support them.However there is no problem with Ref cursors . How to resolve?.
Please try searching the JDBC discussion forum or try reposting the question in the JDBC forum. The url is:
http://forums.oracle.com/forums/forum.jsp?forum=99 -
Table Type Stored Procedure in OBIEE Physical table properties
Hi,
Any one has ever used the Stored Procedure in OBIEE Physical table properties??
I've a procedure & a table i want to plopulate the tabel using the Procedure from OBIEE physical layer.It would be nice if we know more details about 'Populating table'...
Using connection pool->connection pool scripts tab you may go for inserting/updating (Populating table) records into table.
It would be nice if you use dedicated connection pool for init blocks...
Ex: I want to insert user login time some xyz table my query would be like
insert into xyz values ('valueof(NQ_SESSION.USER)',sysdate)
without knowing your requirements its hard to tell anything apart from what is said.
If helps pls mark
Edited by: Srini VEERAVALLI on Jan 16, 2013 10:37 PM -
Use of Procedure and Functions in ADF BC
Hi,
In ADF 11g
1. can I use oracle function and procedures ( having in and OUT parameters) to expose as service interface
2. if yes , How can this be done. and what are the allowed data types as input to procedure/function and can be returned by procedure/function
3. How the transaction control will be achieved using ADF BC service interface.
E.g. one ADF BC creates orders in order details and second creates Order lines in Order lines table. Now if order is created successfully but line creation fails then I want order to be rolled back also.
Thanks.google it out.
How to get two out param which is used in Procedure
http://sameh-nassar.blogspot.in/2010/01/create-plsql-function-and-call-it-from.html
http://adf-tools.blogspot.in/2010/09/adf-function-call-from-el-statement-in.html
http://adf-tools.blogspot.in/2010/03/adf-plsql-procedure-or-function-call.html
http://adfhowto.blogspot.in/2010/11/call-db-procedure-or-function-from-adf.html
Re: use of Procedure and Functions in ADF BC -
Stored procedure and coldfusion.
Hi all,
My query is related with Oracle and coldfusion. I have got to write a stored procedure for updating a table. In this I have to raise an exception if the field i give for does not exist. Can anyone give an example code for this? I also want to know how it is called in a cfm page.
Following is the stored procedure i have written
create or replace package group_pack
as
procedure group_update
pt_group_id in group.group_id%type,
pt_group_name in group.group_name%type
end;
create or replace package body group_pack
as
procedure group_update
pt_group_id in group.group_id%type,
pt_group_name in group.group_name%type
as
begin
update group
set group_id = pt_group_id,
group_name = pt_group_name
where group_id = pt_group_id;
exception
when no_data_found then (what to code)
end;
end;
In this in the (what to code) part i tried returning zero...but then procedures do not return values. Then I tried to RAISE exception, which also showed error.
Also in the cfm page what should be done with the <cfstoredproc> </cfstoredproc>tags. How should it be reflected.....
Please do give a solution to my problem.....
Thanking in advance....
Regards,
Aswathy.Hi Aswathy,
Can you please tell, what error it gave when you had written RAISE command? I think, this is a better choice if you do not want to do anything else like inserting a row with the missing value.
regards,
Archana
http://justoracle.blogspot.com/ -
Regarding Procedures and functions
can we pass a cursor,table or ref cursor to a procedure and functions and can a function return cursor,table or ref cursor to a procedure and functions?please if possible give some examples with explanations
thanks in advance..Hi,
The definition for a Procedure or Function can be edited by selecting Edit from the drop-down menu for the Procedure/Function object in the Browser.
The definition can then be edited as text, and so Table, REF CURSOR, ... parameters or return types can be added.
(After completing the edit, select Save from the File menu, or alternatively Close the tab displaying the definition and select Yes to the Save Changes dialog.)
The Oracle Database PL/SQL Language Reference documentation contains some examples of Procedure and Function definitions.
David -
Are the Pl/sql procedure and function atomic by themself
i want to ask a question does oracle pl/sql procedure and function support Atomicity for the database by themself , or they became atomic incase we call them using begin -- end;
You appear to be discussing transaction scope which is completely independent of PL/SQL blocks like procedures or how you call procedures. It's all in where commits (or rollbacks) are issued.
If you have a procedure like this
CREATE PROCEDURE p1
AS
BEGIN
INSERT INTO some_table( key, value ) VALUES( 1, 'Foo' );
INSERT INTO some_table( key, value ) VALUES( 1, 'Bar' );
END;where the first statement succeeds and the second statement fails as a result of a duplicate key, there will still be a Foo row in the table but the procedure will have thrown an exception. The caller of the procedure may choose to commit or rollback the change-- that will determine whether the first statement's results are made permanent. If you have a procedure like this,
CREATE PROCEDURE p1
AS
BEGIN
INSERT INTO some_table( key, value ) VALUES( 1, 'Foo' );
commit;
INSERT INTO some_table( key, value ) VALUES( 1, 'Bar' );
END;the commit will make the first insert permanent regardless of whether the second statement fails no matter what the calling code does (that's one reason that putting commits in stored procedures is generally a bad idea-- the caller is in a much better position to know what other uncommitted work has been done and whether it is safe to commit.
Justin
Maybe you are looking for
-
I have put itune code on the wrong email address how can I transfer it to my current email address please?
-
HT1689 How do I add another user to my iTunes account?
Is it possible to add another user to my iTunes account? Thx!
-
Since upgrade iTunes is not playing correctly
Since I have upgraded to the new software my music is not playing correctly? Not sure how to correct it. Help please
-
Please How can I capture and integrate a single pulse of a DC signal from an external circuit
Hello everyone I am trying to integrate a signal from an external circuit I have built. I want to capture just a single pulse from the signal and integrate it. Please can anyone assist me with how I can perform this?
-
Hi All, I want to convert from decimal (5, 2) to decimal (3,0) in data services. if anybody knows please let me know with syntax.