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
Similar Messages
-
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 -
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, KLDYour 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. -
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 -
What is the difference between procedure and function?
Hi,
i want to know the difference between procedure and function.
Also, i want to know types(if they exists) of procedures and functions .
RegardsAlso, please try and use the SEARCH functionality offered by the forum, it's always possible someone has asked the question before you.
Functions vs Stored Procedures
Is one such instance. -
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 -
Differences between procedures and functions.
a little confusing ..in differences between procedures and functions..
1. Can a function return only single value?? cant we return multiple values?
2. Can we use 'out' parameter and 'return' clause at a time in the same function
thank youHi,
newbie wrote:
a little confusing ..in differences between procedures and functions..
1. Can a function return only single value?? cant we return multiple values?Yes, a function can only return a single value.
If the return type is some kind of collection or data structure, then that 1 collection or data structure can, of course, actually contain many sep[arate values.
If you want to return multiple values, use a PROCEDURE with multiple OUT arguments. (Functions can have OUT arguments, too, but avoid defining functions with OUT arguments. It can cause a lot of confusion.)
2. Can we use 'out' parameter and 'return' clause at a time in the same functionSure, but don't take my word for it. Try it and see. -
Difference between procedure and function
hi
please give solution to below discussion:
Interviewer: What is the difference between Procedure and Function ?
Myself: Procedure may or may not return a value and can return multiple values and Function must return a value.
Interviewer : Can function return multiple values ?
myself: Yes, It can return multiple values.
Interviewer: Then, there is no need to use procedures any more, according to your previous answer (function can return multiple values) "we can do all the things by using procedures by using functions". Then why there is differentiation between procedure and function ?
myself : no reply (simply frustated at this question)
The above is conversation between me and interviewer.
Please suggest me what would be my reply to above topic.
In one book i find that using functions we can return multiple values but it is poor programming practice.
why this is a programming practice ?
please suggest me solution
thanks in advance
prasanth as.Another difference is function must return something. There is no such restriction on procedure.In fact, a procedure CANNOT contain an expression in its RETURN statement.
SQL> create or replace procedure test_return is
2 begin
3 return(10) ;
4 end ;
5 /
Warning: Procedure created with compilation errors.
SQL> show errors
Errors for PROCEDURE TEST_RETURN:
LINE/COL ERROR
3/3 PLS-00372: In a procedure, RETURN statement cannot contain an
expression
3/3 PL/SQL: Statement ignored
SQL>And, a procedure cannot be called as part of a expression (it must be a function).
SQL> create or replace procedure test_return is
2 begin
3 return ;
4 end ;
5 /
Procedure created.
SQL> variable x number ;
SQL> exec :x := test_return ;
BEGIN :x := test_return ; END;
ERROR at line 1:
ORA-06550: line 1, column 13:
PLS-00222: no function with name 'TEST_RETURN' exists in this scope
ORA-06550: line 1, column 7:
PL/SQL: Statement ignored
SQL> -
Plz give the difference between procedure and function atleast 10 differenc
plz give the difference between procedure and function atleast 10 differenc
From http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14251/adfns_packages.htm#i1006378
>
The only difference between procedures and functions is that functions always return a single value to the caller, while procedures do not return a value to the caller.
>
Edited by: P. Forstmann on 28 oct. 2010 15:30 -
Difference between a "stored procedure" and a "procedure defined in package
Hi,
Is there any difference between a "stored procedure" and a "procedure defined in package"
thanks in advancehttp://download.oracle.com/docs/cd/B19306_01/appdev.102/b14251/adfns_packages.htm#sthref779
Steps
http://www.oracle.com/pls/db102/homepage
http://www.oracle.com/pls/db102/search?word=stored+procedure+package
5th result -
UCCX 8 - Custom Stored Procedure Not Functioning
Hello,
We're trying to modify one of the agent summary reports in UCCX 8. We want the outbound report to only show numbers that were external calls. (Longer than 4 digits.) We copied and modified the existing stored procedure and it seems to run ok until we try to use it in the historical reporter. HR reports that the stored procedure cannot be found. We've followed what documentation we could find about adding one but can't get it working. We've been using ASG Server Studio to access the database. We opened a TAC case but haven't gotten anywhere. Here's the detail we gave them.
/* Style Definitions */
table.MsoNormalTable
{mso-style-name:"Table Normal";
mso-tstyle-rowband-size:0;
mso-tstyle-colband-size:0;
mso-style-noshow:yes;
mso-style-priority:99;
mso-style-qformat:yes;
mso-style-parent:"";
mso-padding-alt:0in 5.4pt 0in 5.4pt;
mso-para-margin:0in;
mso-para-margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:11.0pt;
font-family:"Calibri","sans-serif";
mso-ascii-font-family:Calibri;
mso-ascii-theme-font:minor-latin;
mso-fareast-font-family:"Times New Roman";
mso-fareast-theme-font:minor-fareast;
mso-hansi-font-family:Calibri;
mso-hansi-theme-font:minor-latin;
mso-bidi-font-family:"Times New Roman";
mso-bidi-theme-font:minor-bidi;}
I have created a stored procedure on the informix DB for UCCX 8. i have
been following the Historical reporting admin guide. the SP runs fine when i use ASG
server studio. when i try to use crystal reports to access the SP i get "Failed to
retrieve data from the database. Details: ADO Error code 0x80004005 Source: Microsoft OLE
DB Provider for ODBC Drivers Description: [Informix][Informix ODBC Driver][Informix]
Routine (sp_agent_call_summar_nointernal) can not be resolved. SQL State:S1000"
if i use a standard procedure Crystal Reports works fine.
i have the uccxHrUserRole assigned to the procedure so i do not understand why i cannot
run the SP.
Any ideas, we really need to get this working.
Thanks!Hi
1) There are an impressive number of bugs in early 8.0 versions; on the initial release permissions were incorrect for the existing SPs so the uccxHrUser couldn't run them. You could copy them, so had to copy them and run the copies.. tedious.
If you are on a working version, the other gotcha is that you need to specify them fully-qualified - so sp-test would be db_cra.dbo.sp_test
Also note that the SPs are randomly split between 'functions' and 'procedures' (there may be a pattern, but I can't work it). Both are similar, but there is a field in the DB that marks a proc as a fucntion or a procedure - the informix Squirrel SQL plugin doesn't work well with this and just shows the ones marked as 'procedures'. I've had better luck with RazorSQL and have recently played with the free IBM Data Studio which I think also displayed them all.
2) You can't edit the permissions of existing ones, but you can add new ones and since you (well, uccxHrUser) is the owner you can set permissions on those. Try using RazorSQL or AGS Server Studio (which is better, but $$$) to add new procs.
Aaron
Please ratre helpful posts.. -
Relation between Tax procedure and Pricing procedure
Dear All,
I would like to get more clarity on Tax procedure, Pricing procedure.
a) Why do we have Tax procedure and assigned to Country?
b) If the tax procedure has been created and assigned to Country-IN (in FI module), then why do we need to create pricing procedure with same condition type for purchasing in MM module? We are even creating lot of pricing procedure for Sales in SD module.
Regards
Manivannan RHi
Tax
During SD document transactions, tax calculation procedure TAXUSX is only relevant to determine the tax liability accounts for output sales tax. Notice that in pricing procedure RVAXUS, the condition types XR1 - XR6 carry the tax rates and tax amounts - resulted from the external tax system calculation - which is posted to tax G/L accounts. However, the tax accounts are not specified in the pricing procedure but rather in the tax calculation procedure.
Tax codes are the link between pricing procedure and tax calculation procedure.
Pricing
The primary job of a pricing procedure is to define a group of condition types in a particular sequence. The pricing procedure also determines:
Which sub-totals appear during pricing
To what extent pricing can be processed manually
Which method the system uses to calculate percentage discounts and surcharges
Which requirements for a particular condition type must be fulfilled before the system takes the condition into account
Example
Example of a Pricing Procedure
If a sales department processes sales orders for a variety of foreign customers, the department can group the customers by country or region. A pricing procedure can then be defined for each group of customers. Each procedure can include condition types that determine, for example, country-specific taxes. In sales order processing, you can specify pricing procedures for specific customers and for sales document types. The system automatically determines which procedure to use.
Pricing Procedures in the R/3 System
The standard system contains pre-defined pricing procedures, which contain frequently used condition types along with their corresponding access sequences. You can, of course, modify these procedures or create your own from scratch.
Creating and Maintaining Pricing Procedures
You create or maintain pricing procedures in Customizing for Sales. For more information on creating pricing procedures, see the online Implementation Guide for Sales and Distribution.
To reach the pricing procedure screen from SD Customizing:
1. Choose Basic Functions
2. ® Pricing ® Pricing control ® Define and assign pricing procedures.Select the transaction that you want to execute. -
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 -
Difference in between account currency and functional currency
Hi Sap Experts,
What is the difference in between account currency and functional currency.
In which table account currency and functional currency will be stored.
Regards,
Rajprabhakar
Moderator: Please, avoid asking basic questionsA Payer is the individual or company who settles the invoices foa a service or for delivered goods.
Whereas the account group determines:
Which screens and fields are necessary for entering master data
Whether you can or must make an entry in these fields
How master record numbers are assigned (externally by you or internally by the system) and the number range from which they are assigned
Which partner functions are valid
Whether the business partner is a one-time customer or one-time vendor.
Reward if useful.
Amruta -
Without calling stored procedure or functions from database
Hi,
I am using Jdeveloper 11.1.1.5.0.
=>How to do PL/SQL procedures and functions in ADF without calling stored procedure or function from DB?S, PL/SQL procedures and functions are done in Application Module class or in managed bean..By calling the stored procedures or functions from DB.
But I am asking how to do if DB doesn't have any procedures,triggers and functions.
Maybe you are looking for
-
Request in Reply Payload Problem
I am attempting to build a component which takes our common xml payload, passes it through a Mediator and then off to an external service. In the response I need to copy values from the request object and pass back to caller. In my mediation activity
-
Problem with adapter network category reverting to public after change to private
I noticed that after setting up HyperV Server 2012 R2, that after applying needed firewall rules to allow remote management, that these were added into the "Public" profile. So, I disabled them and enabled for Private and proceeded to change the NIC
-
Ierrs on 3C905B over NFS on solaris 8 x86
I have 2 identical Dell PC's, one with Solaris 8 HW 07/01 and one with Solaris 2.6 On the Solaris 8 box, when copying files to local disk over NFS, I get lots of ierrs on the elxl0 devices and the copy is very slow (NFS server is a netapp with gigabi
-
Styling of controls does'nt work programmatically
Hallo, I have a stylesheet (mystylesheet.css) with following entry: .flowpane{ -fx-background-color: rgb(0,0,0); in then start-method of my application I execute: StackPane root = new FlowPane(); Scene scene = new Scene(root,
-
Accessing Long datatypes using JDBC
Can any body help me how to access long datatypes in JDBC. I need to store large data in String object arround 100000 length string in long. as of now with pstmt.setString(1,String ) i am able to insert 32700 length string only . how can i over come