SQL Queries in Code V/s Stored Procedures

Hi Friend,
Can any one of you guide me with following..
What is faster ? using SQL Queries in Java code or using Stored Procedures which are called from code?
I understnd Stroed Procedures are faster and definitely it provides more maintainability.
If any one can give me any links or resources which outlines pros and cons of using Stored Proc and SQL Queries embedded in Java than it would be a great help..
If there are any articles which proves either of the above is a preferred way, that would also help..
Appreciate the effort in advance !!
Thanks
Gurudatt

Well one benefit of Stored Procs is that you "compile" it on the database whereas you might build your query on the fly in java... test coverage is important in order not to have such things as a typo in a column name....
Still, if you change a table, you have to go through all the procedures in SQL and likely to do so in some of your business object... and trust me, that can be hell!
It all depends on the use of the app...
From my experience, Stored procedure are much faster than built-on-the-fly SQL (and quite faster than prepared statements depending on the JDBC driver, the re-use of connections etc...)....
IMHO, you'd probably be wise to start of with prepared statements, and when the schema seems stable enough (ie unlikely to change), look for the slower queries and convert them to stroed procedures.
If you don't have to support several databases and are tight on performance, you can even include some logic in your stored procedure (e.g. update several tables, based on various selects...etc...). The language is usually quite powerful, and that can save you the run-time of selecting, converting to object , process and update (i.e. several roud-trip between DB and app)...
Tshcuss!
Chris

Similar Messages

  • Extracting the DDL(Code) of only stored procedures

    DB Version:11g
    I have a list of Stored procedures (about 250) whose code ie. CREATE OR REPLACE STORED PROCEDURE statements i want to extract to a file.
    Is there an option in imp or impdp where i can extract only the code of these stored procedures?
    Apart from imp/impdp , is there any other way to do this?

    Is there an option in imp or impdp where i can extract only the code of these stored procedures?impdp, Yes. Write the contents to a file using, SQLFILE option.
    DUMPFILE = exp.dmp
    LOGFILE = exp.log
    SCHEMAS=TEST
    INCLUDE= PROCEDURE:"IN ('SP')"
    SQLFILE=sp..sql
    Or use dbms_metadata.get_ddl
    set long 99999
    set pagesize 0
    SELECT DBMS_METADATA.GET_DDL(object_type, object_name, owner) FROM DBA_OBJECTS WHERE OBJECT_TYPE = 'PROCEDURE' and OWNER='OWNER';HTH
    -Anantha

  • Central Administraion Internal server error 500 | event id 5586 sharepoint foundation unknown sql exception 2812 could not find stored procedure dbo.proc_gettimerlock

    Hi,
    We have two SharePoint 2010 SP2 servers with one SQL 2012 Backend.
    Recently we cannot open the central administration, getting 500 internal server error and multiple SQL errors in event viewer:
    event id 5586 sharepoint foundation unknown sql exception 2812 could not find stored procedure dbo.proc_gettimerlock
    event id 5586 sharepoint foundation unknown sql exception 2812 occured could not find stored procedure 'proc_fetchdocforhttpget'
    Also I cannot run SharePoint configuration wizard, getting this error: sharepoint 2010 failed to resgister sharepoint services
    In the log file, I found this error "an exception of type microsoft.sharepoint.spexception was thrown 0x80131904"
    Any ideas?
    Thanks, Shehatovich

    As You can see below stored procedure has its specific Permission's, check user who is performing action as well as CentralAdministation Pool has right permission and their permissions are not modified from SQL Server.
    -Samar
     =
    Sr. Software engineer

  • Dynamic sql and block based on a stored procedure

    Hi!
    I'm triying to generate a block based on a stored procedure. I want the stored procedure to execute a dynamic sql, but I'm having getting the error "PLS-00455 cursor 'AULOCASLATE' cannot be used in dynamic SQL OPEN statement".
    I have the following code:
    CREATE OR REPLACE package pkg_f0015 is
    type rClieInstSlate is record
    (clie_id CMS_CLIENTS.ID%type
    ,client_nm varchar2(1000)
    ,cs_no CMS_CLIENTS.CS_NO%type
    ,dob CMS_CLIENT_NAMES.BIRTH_DT%type);
    type tClieInstSlate is table of rClieInstSlate;
    type uClieInstSlate is ref cursor return rClieInstSlate;
    procedure prLocationSlateQry(
    auLocaSlate in out uClieInstSlate,                anCsNo in CMS_CLIENTS.CS_NO%type,
    avClieNm in varchar2,
    avSearchType in varchar2,
    avLotyCd in CMS_LOCATION_TYPES.CD%type);
    end pkg_f0015;
    CREATE OR REPLACE PACKAGE BODY pkg_cms_f0015 is
    procedure PRLocationSlateQry( auLocaSlate in out uClieInstSlate,
    anCsNo in CMS_CLIENTS.CS_NO%type,
    avClieNm in varchar2,
    avSearchType in varchar2,
    avLotyCd in CMS_LOCATION_TYPES.CD%type) IS
    vSelect varchar2(5000);
    vAddCond varchar2(1000);
    vSupLevel varchar2(50);
    begin
    vSelect := 'select clie.ID,'||
    ' CLIENT_NAME,'||
    ' clie.CS_NO,'||
    ' clna.BIRTH_DT dob'
    ' from CMS_CLIENT_NAMES clna,'||
    'CMS_CLIENTS clie'||
    ' where clna.CLIE_ID = clie.ID';
    if avSearchType= 'C' then
    vAddCond := ' and clie.CS_NO = nvl('||anCsNo||',clie.CS_NO)';
    vSelect := vSelect || vAddCond;
    open auLocaSlate for vSelect;
    end if;
    end PRLocationSlateQry;
    end;
    I wonder if what I want is possible

    OK,
    Now it works. Previously we had the parameter p_guid declared as RAW, which obviously is not any good. :)
    Radovan
    Edited by: biciste on Apr 28, 2009 4:57 PM

  • SQL server Query to sort the Stored procedure as text

    Hi
    I have a requirement as below :
    Stored procedure in SQL server has some 1000 lines of code where the SP uses select, insert , update ,delete and Joins on direct tables and as well as temp tables , the requirement is to get all text code from sp which is used for either select/insert
    except update and delete.
    for example :
    Create PROCEDURE testproc
    AS
    Begin
    /*Statement 1*/
    select id from emptable
    /*Statement 2*/
    select address into #empAddress from empAddresstbl
    /*Statement 3*/
    update a
    set id = 0 from usertbl a 
    /*Statement 4*/
    Update u
    set access=0 from usertbl u
    inner join permissionstbl p
    on u.userid = p.userid
    /*Statement 5*/
    select name into #empname
    from empnametbl
    inner join Nametbl on
    empname.id = name.id
    END
    for the given sample sp the output of query shld be
    from emptable
    from empaddresstbl
    from empnametbl
    join nametbl
    it shld not consider the table name from update/delete and the tables used for joins in updates/delete.
    This has to be achieved using  SQL
     Thanks,

    Hi All,
    Problem is solved after adding files to microsoft access 2000 runtime. runtime missing some DLLs related to sql server 2000 to update those files follow the links below
    http://support.microsoft.com/?kbid=287484
    http://www.microsoft.com/office/orkarchive/2000ddl.htm#accsql
    Thanks,
    Brahma

  • Running multiple queries in parallel in a stored procedure

    Hi,
    I have two queries one on table1 (group bys) and second on table2 (again group bys) and then I need to compare the results.
    Is it possible to execute both of them in parallel as they have no dependencies ? SInce it is going to be called from a JAVA program right now the only way I know is
    to execute them in multiple threads but it would be great to have ideas of how to do it in a stored procedure. As a series of steps(all sql quries) have to be carried out and
    the data has to be locked for that period ?
    Just for clarity the steps are :
    Step1 : select for update cursor to lock the rows from table1
    Step2: open curosr then select data from table1 --- perform validations
    Step3 : select data using group bys on table1 and select data using group bys on table2 ---- this needs to be done in parallel (just to gain on time)
    Step4 : compare data
    Step5 : insert statement
    Step6 : close cursor then commit and exit
    This might be really silly question but please pardon my ignorance as I am not much of SQL guy !
    Thanks,
    Neetesh
    Edited by: user13312817 on 10 Nov, 2011 8:27 AM

    Maybe something like this (not tested)?
    SELECT t1.referenceno
         , t1.col1
         , t1.col2
         , t1.entityparent
         , t1.class
         , t1.annual - t2.annual
    FROM   (
              SELECT table1.Referenceno
                   , table1.col1
                   , table1.col2
                   , entitycodes.entityparent
                   , classes.class
                   , SUM(nvl(table1.AnnualAmt,0)) as Annual
              FROM   table1
              JOIN   entitycodes ON entitycodes.entitycode = table1.fundentity
              JOIN   classes     ON classes.accountcode    = table1.account
              GROUP BY table1.Referenceno
                     , table1.col1
                     , table1.col2
                     , entitycodes.entityparent
                     , classes.class
         ) t1
    JOIN    (
              SELECT table2.Referenceno
                   , table2.col1
                   , table2.col2
                   , entitycodes.entityparent
                   , classes.class
                   , SUM(nvl(table2.AnnualAmt,0)) as Annual
              FROM   table2
              JOIN   entitycodes ON entitycodes.entitycode = table2.fundentity
              JOIN   classes     ON classes.accountcode    = table2.account
              GROUP BY table1.Referenceno
                     , table1.col1
                     , table1.col2
                     , entitycodes.entityparent
                     , classes.class
         ) t2 ON  t2.referenceno  = t1.referenceno
              AND t2.col1         = t1.col1
              AND t2.col2         = t1.col2
              AND t2.entityparent = t1.entityparent
              AND t2.class        = t1.class

  • Tools/Preferences/Code Editor/Link Stored Procedures to Files

    Found this option, sounds promising. Is there for real a way to establish link between a stored procedure code and a file?
    There is gap in help file; it jumps from "Max Open PL/SQL Editors" straight to "Auto-Indent New Lines"
    Sincerely
    Alek

    This is for file-based debugger support (can't locate exact SQL Dev exchange reference). It works the following way. Open file based PL/SQL compilation unit, select connection. Press the "compile with debug" info tool button. Now file based and database units are linked together witnessed by a record in project.qbql file in sql dev preferences directoory. Now you can set breakpoints in file based source and when stepped into a called procedure(s) you'll be directed to file-based sources as well, (provided they are linked the same way).

  • Need sample source code for calling stored procedure in Oracle

    Hi.
    I try to call stored procedure in oracle using JCA JDBC.
    Anybody have sample source code for that ?
    Regards, Arnold.

    Thank you very much for a very quick reply. It worked, but I have an extended problem for which I would like to have a solution. Thank you very much in advance for your help. The problem is described below.
    I have the Procedure defined as below in the SFCS1 package body
    Procedure Company_Selection(O_Cursor IN OUT T_Cursor)
    BEGIN
    Open O_Cursor FOR
    SELECT CompanyId, CompanyName
    FROM Company
    WHERE CompanyProvince IN ('AL','AK');
    END Company_Selection;
    In the Oracle Forms, I have a datablock based on the above stored procedure. When I execute the form and from the menu if I click on Execute Query the data block gets filled up with data (The datablock is configured to display 10 items as a tabular form).
    At this point in time, I want to automate the process of displaying the data, hence I created a button and from there I want to call this stored procedure. So, in the button trigger I have the following statements
    DECLARE
    A SFCS1.T_Cursor;
    BEGIN
    SFCS1.Company_Selection(A);
    go_Block ('Block36');
    The cursor goes to the corresponding block, but does not display any data. Can you tell me how to get the data displayed. In the future versions, I'm planning to put variables in the WHERE clause.

  • Help : To convert Following Code into oracle Stored Procedure

    Hi All
    I m Ajay Patel
    N i m new in Oracle i don't know much abt oracle
    I want to convert following code in to oracle10g ( Procedure )
    This is PHP code n this function abt compound interest.
    $pa,$ri,$sy,$ey :- all are in parameters
    all variable declare with $
    $pa - is principle amount
    $ri - Rate
    $sy - start year - 2009
    $ey - end year - 2060
    function CCI($pa,$ri,$sy,$ey)
              $CCI = array();
              $totalyear = $ey - $sy;
              $ri = $ri/100;
              $ri= 1 + $ri;
              $amt=1;
              for($i=1;$i<=($totalyear+1);$i++)
                   if($i==1)
                        $CCI[$i][0] = $sy;
                        $CCI[$i][1] = $pa;
                   else
                        $powvalue = 1;
                        for($k=1;$k<$i;$k++)
                             $powvalue = $ri * $powvalue;
                        $FinalValue = $pa * $powvalue;
                        $CCI[$i][0] = $sy;
                        $pos = strpos($FinalValue, '.');
                        if ($pos !== false)
                             $FinalValue =     substr($FinalValue, 0, $pos+3 );
                        $CCI[$i][1] = $FinalValue ;
                   $sy++;
              return $CCI;
    Pls Help Me to convert above code in to oracle stored procedure
    Thanks All
    Regards,
    Ajay

    Its time to start reading the Document .

  • Change code in multiple stored procedures

    Hi,
        I have many stored procedures that have the server name hard-coded for bcp out purposes.  Is there a was to update all of these at one time, or am I stuck opening each one up seperately?
    Thanks
    Pam

    You can generate the ALTER scripts for all your stored procedures and then search-and-replace.
    David
    David http://blogs.msdn.com/b/dbrowne/

  • Can't map Booleans from native SQL queries with Code First, EF 6, ODAC 12c R3 (Beta 2)

    We're using Code First, EF 6, ODAC 12c R3 (Beta 2). When I use LINQ-to-Entities, I can map NUMBER(1) to Boolean fields as documented here: https://docs.oracle.com/cd/E56485_01/win.121/e55744/entityDataTypeMapping.htm#ODPNT8300
    <oracle.manageddataaccess.client>
      <version number="*">
      <edmMappings>
        <edmMapping dataType="number">
          <add name="bool" precision="1"/>
          <add name="byte" precision="3" />
          <add name="int16" precision="4" />
          <add name="int32" precision="9" />
          <add name="int64" precision="18" />
        </edmMapping>
      </edmMappings>
      </version>
    </oracle.manageddataaccess.client>
    So far, so good:
        [Table("USER_PROFILE")]
        public class UserProfile
            [Key]
            [Column("LOGIN_ID", Order = 1)]
            public string LoginId { get; set; }
            [Column("IS_SUPER_USER")]
            public bool? IsSuperUser { get; set; }
    var query = db.UserProfiles.Take(20);
    However, when I try to map to the same class from native SQL, I get an exception:
    // The real query is much more complex. This is just an example.
    private const string AllProfilesSql = @"
                SELECT login_id AS LoginId, is_super_user AS IsSuperUser
                FROM user_profile
    var query = db.Database.SqlQuery<UserProfile>(AllProfilesSql).Take(20);
    >The 'IsSuperUser' property on 'UserProfile' could not be set to a 'System.Int16' value. You must set this property to a non-null value of type 'System.Boolean'.
    Do you know any solutions or workarounds for this? Is it a bug?

    Hmm, a feature request is possible; however, I'm not sure how feasible it would be to implement (if it is possible at all) in this scenario.
    The challenge is that when using SqlQuery like this, EF calls into our override of the ExecuteDbDataReader method in OracleCommand (via System.Data.Common.DbCommand.ExecuteReader). That in and of itself is not an issue it's just that we don't know that this call is from EF and so we should use the EDM mappings from the configuration. In a "normal EF" scenario we know the call is from an EF "source" so can respond accordingly and perform the mapping.

  • How to pass the parameter values to the stored procedure from java code?

    I have a stored procedure written in sqlplus as below:
    create procedure spInsertCategory (propertyid number, category varchar2, create_user varchar2, create_date date) AS BEGIN Insert into property (propertyid, category,create_user,create_date) values (propertyid , category, create_user, create_date); END spInsertCategory;
    I am trying to insert a new row into the database using the stored procedure.
    I have called the above procedure in my java code as below:
    CallableStatement sp = null;
    sp = conn.prepareCall("{call spInsertCategory(?, ?, ?, ?)}");
    How should I pass the values [propertyid, category, create_user, create_date) from java to the stored procedure?[i.e., parameters]
    Kindly guide me as I am new to java..

    Java-Queries wrote:
    I have a stored procedure written in sqlplus as below:FYI. sqlplus is a tool from Oracle that provides a user interface to the database. Although it has its own syntax what you posted is actually PL/SQL.

  • How to handle stored procedure response having multiple queries

    Hi Friends,
    While working in JDBC to RFC scenario,I faced an issue that my stored procedure is having multiple SQL queries in it. First Select and then update and again some select options.So,how to handle the response of the stored procedure. I read that while using sender JDBC
    " db.processDBSQLStatement=<SQL-Select-Statement>
    Either specify a valid SQL SELECT statement to select the data to be sent from the specified database, or specify an SQL EXECUTE statement to execute a stored procedure that contains exactly one SELECT statement  "
    So, please suggest me is there any other way to catch the output of the stored procedure.Because, if select statement is working fine but if any other quires fails then data inconsistencies can happen.Kindly help me out.
    Thanks and Regards,
    Nutan

    Hi nutan,
    >>Already exception is handled in SP.But,issue is that select will never fail so, sender adapter will get the resultset from select and continue process.But if later any other query fails in SP adpter wont be getting any response.
    Along with exception you need to handle the case when some other query fails. A SP is like a procedure which will do a certain list of activities before providing the output. So during this activity if some query fail then you can send back the response with a message!!!! And in XI handle this error (by routing it to some error receiver etc)
    >>I need to try something like creating a temporary table and inserting the resultset of slect statement in that. and perform all other operations and after successful completion of all the queries.Again i want to get all the values from the temporary table. So,whether I can write such query in the sender communication channel.Please suggest me for this.
    Approach looks ok, but think of the delay for JDBC sender adapter. IT will invoke your SP and will wait for it to fill a table and do all the processing. I guess this may become a issue for you.
    Check on the frequency of this interface and message size before taking this design approach
    Regards
    Suraj

  • User can Execute SQL Statement but not Stored Procedure

    I have a function in Access that calls a stored procedure to update a table. When I run it, it works fine but when the users try to run it, they get an error.
    If I change it run the actual SQL syntax that is in the stored procedure then the users can run it and update the table without any problems, which makes no sense to me. It's doing the same exact thing as the stored procedure. I'd much rather have them be
    able to run the procedures then writing the SQL in VBA modules because that's going to end up being a lot of code.
    Any idea on why it's like this and how to correct it? Any assistance would be appreciated.

    Hello,
    When you give a user permission to run a stored procedure, everything on that procedure but Dynamic SQL will be executed
    without evaluating user permissions on the objects the stored procedure deals with.
    On the link I provided above, you will see how to provide permissions to stored procedures. Try creating database roles, add user to database roles, then assign permissions to database roles.
    Hope this helps.
    Regards,
    Alberto Morillo
    SQLCoffee.com

  • Issue with Oracle.sql.NUMBER in Java Stored Procedure

    When we try to make a call to the Oracle.sql.NUMBER(String) inside a java stored procedure and pass values from '01' to '09', it throws java.lang.StringIndexOutOfBoundsException: String index out of range: 3
    We use Oracle 9.2.0.6 - JServer Release 9.2.0.6.0.
    It works fine for other values. Please find below the code used for simulating the issue outside the application. Thanks.
    create or replace and compile java source named testNumber as
    import oracle.sql.NUMBER;
    import java.sql.SQLException;
    public class TestNumber
           public static String convertNumber(String parm) {
                     NUMBER nTest;
                     try {
                             nTest = new NUMBER(parm);
                             return "TRUE";
                     }catch (SQLException sqle) {
                             return "FALSE";
    create or replace function test_number (p_str in varchar2) return varchar2 as
    language Java name 'TestNumber.convertNumber(java.lang.String) return
    java.lang.String';
    select test_number('05') from dual;  - Throws exception ORA-29532: Java call terminated by uncaught Java exception: java.lang.StringIndexOutOfBoundsException: String index out of range: 3
    select test_number('5') from dual; - Works fine
    select test_number('010') from dual; - Works fine

    Siva,
    I'm only guessing, but it could be an Oracle bug, in which case I suggest checking with Oracle Support.
    (You do have a support contract, don't you? ;-)
    Did you try compiling and running your java class "TestNumber" outside the database?
    Class "oracle.sql.NUMBER" should be in Oracle's JDBC driver, I believe.
    Good Luck,
    Avi.

Maybe you are looking for