Stored Procedure Concurrency

I'm using Java to connect to a SQL Server 2000 database. I connect using the Driver Manager with Sun's odbc driver ( sun.jdbc.odbc.JdbcOdbcDriver ) or I can use the jdbc driver provided by Microsoft (com.microsoft.jdbc.sqlserver.SQLServerDriver)
The Java application makes 1 Connection.
Within the database there exists a stored procedure that updates 2 Tables. The tables have a fixed number of rows that get updated continuously by calls to this stored procedure.
The Java application has a thread pool of 15 threads that create 15 CallableStatements (1 per thread) using the same instance of the Connection object.
According the the Microsoft JDBC driver docs, 1 Connection with multiple calls to the Callable statements is how it's supposed to be done. The following is an excerpt from Microsoft's "SQL Server 2000 Driver for JDBC User�s Guide and Reference" (page 86) regarding Connection Managment:
Managing Connections
Connection management is important to application performance. Optimize your application by connecting once and using multiple statement objects, instead of performing multiple connections. Avoid connecting to a data source after establishing an initial connection.
This is precisely what I'm doing, but I do not know if the the stored procedures are be run concurrently, the documentation does not tell me.
So my question: What is happening inside SQL Server 2000?

The Java application has a thread pool of 15 threads
that create 15 CallableStatements (1 per thread)
using the same instance of the Connection object.I believe this is bad and you're just asking for trouble. Each thread should have its own Connection - Connections are not thread-safe.

Similar Messages

  • Stored Procedure Concurrency Problem 10g

    dear all,
    Please any one could help on this my problem is appreciated.......
    i'm generating ticket numbers using stored procedure as below .
    i need to know followings .....(i'm using oracle 10g)
    1 .Does oracle stored procedure handle concurrency by default or does db manage concurrency when we using sps or do we have handle concurrency inside a stored procedure?
    2.when i generating ticket no using this stored procedure is there any concurrency issue when 100 clients are access it concurrently???
    3. Is there issue or bug in my java code??????????
    4.I have already used select for update statement but when i used that in db rowlocks are hanging and db become stuck .........
    SELECT serial_no into newSerial FROM SERIAL_TAB WHERE BR_CODE=xbranch AND SCH_CODE = xscheme for update;
    5. and in my where clause i pass branch and scheme eg:SELECT serial_no into newSerial FROM SERIAL_TAB WHERE BR_CODE=xbranch AND SCH_CODE =
    xscheme;
    when i run this sp oracle return the error 'more than one row return by query'
    but when run query seperately it will return exactly one row for same brach code and scheme code no duplicates.
    why this happen and it also happen to update statement it will ignore branch code and update for all schemes
    UPDATE SERIAL_TAB SET serial_no=newSerial WHERE BR_CODE=xbranch AND SCH_CODE = xscheme;
    what should i do ? sorry for my long question since i'm in deep trouble.....................
    could any one can help please................................
    in my java code i use transaction and setAutoCommit(false) when calling this sp
    public String getTicketNo(String br,String sch){
    //getconnection
    //setAutoCommit(False);
    //call sp get return value ;
    //commit;
    //if error rollback transaction
    create or replace PROCEDURE sp_generate_ticket (
    xbranch in varchar,
    xscheme in varchar ,
    xresult OUT VARCHAR
    ) AS
    BEGIN
    newSerial:=0;
    SELECT serial_no into newSerial FROM SERIAL_TAB WHERE BR_CODE=xbranch AND SCH_CODE = xscheme;
    newSerial:=newSerial+1;
    UPDATE SERIAL_TAB SET serial_no=newSerial WHERE BR_CODE=xbranch AND SCH_CODE = xscheme;
    --- do other operations -------------------------------------------------------------------------------------
    END;
    Best Regards,
    Pradeep.
    Edited by: user8958520 on Jan 1, 2012 10:02 PM

    user8958520 wrote:
    i need to know followings .....(i'm using oracle 10g)
    1 .Does oracle stored procedure handle concurrency by default or does db manage concurrency when we using sps or do we have handle concurrency inside a stored procedure?Oracle is a multi-user and multi-process system. It supports concurrency. It also requires the developer to design and write "+thread safe+" code. Its concurrency cannot address and fix design flaws in application code.
    2.when i generating ticket no using this stored procedure is there any concurrency issue when 100 clients are access it concurrently???That depends entirely on WHAT that procedure code does. And whether that code is thread safe.
    4.I have already used select for update statement but when i used that in db rowlocks are hanging and db become stuck .........
    SELECT serial_no into newSerial FROM SERIAL_TAB WHERE BR_CODE=xbranch AND SCH_CODE = xscheme for update;Horrible and utterly flawed approach. This forces serialisation. This means if that procedure is call by a 100 clients, only a SINGLE client can be serviced at a time. ALL OTHERS need to queue and WAIT.
    Serialisation kills database performance.
    What you have is a serious design flaw. Not an Oracle issue. And there is no magic solution to make this flawed approach work in a performant and scalable manner. This flaw introduces artificial contention. This flaw enforces serialisation. This flaw means that your application code WILL step on its own toes time and time again.
    The proper solution is to fix this design flaw - and not use poorly conceived procedures such as sp_generate_ticket that violates fundamental concurrency principles.

  • To find the location of PL/SQL stored PROCEDURE in database

    hi
    this is the detail i ve taken from Application developer-Concurrent Program Executable
    Executable NAPESCO_STAFF_LEDGER_DTLS
    Short Name NPSTALEDDTLS
    Application Human Resources
    Execution Method PL/SQL Stored Procedure
    Execution File name NAPESCO_STAFF_LEDGER_DTLS
    i would like to know how to view and modify this procedure ,where is it stored
    kindly help

    Hi,
    This seems to be a custom package. To view the source of the "PL/SQL Stored Procedure" concurrent program please refer to (Note: 455582.1 - Where Can I Get the Source File of Any 'Pl/Sql Stored Procedure' on Current Program?).
    Thanks,
    Hussein

  • How to run a pl/sql stored procedure as a concurrent program

    Hi All,
    I created a package PURGE_DEAL_REQUESTS. It contains a procedure QPR_DELETE_CANCELLED_REQUESTS. I want to run this stored procedure as concurrent program in ebs suite....
    Can anyone tell me how to run this procedure as a concurrent program(in ebs suite).....?
    Thanks
    Swathi.

    You need to add the concurrent program to the group of the responsibility that will run the report. For more details, please refer to:
    Note: 73492.1 - Creating a PL/SQL Concurrent Program in Oracle Applications
    https://metalink2.oracle.com/metalink/plsql/ml2_documents.showDocument?p_database_id=NOT&p_id=73492.1
    Note: 133991.1 - How to Register a Custom Report
    https://metalink2.oracle.com/metalink/plsql/ml2_documents.showDocument?p_database_id=NOT&p_id=133991.1

  • Creating XML report using PL/SQL Stored Procedure

    Hi Friends,
    I am working on an xml report with the xml source as PL/SQL Stored Procedure.
    I am referring the exercise shown in the following link to understand the process:
       http://orclapp.blogspot.com/2012/02/developing-xml-publisher-report-using.html
    In the example shown in the above link I could not understand the following:
    1) In the following procedure, the out parameter 'retcode' is not used at all.
       What is the importance of this parameter.
        PROCEDURE REPORT (errbuf  OUT VARCHAR2, retcode  OUT VARCHAR2, p_product_id   IN     NUMBER)
    2)  After the xml data is prepared and put to 'l_result' Clob variable, the following
        Loop is executed. I am not able to appreciate why the following loop is required.
         LOOP
             EXIT WHEN l_length = l_retrieved;
             IF (l_length - l_retrieved) < 32000
             THEN
                SELECT SUBSTR (l_result, l_retrieved + 1) INTO l_xmlstr FROM DUAL;
                l_retrieved := l_length;
                fnd_file.put_line (fnd_file.output, l_xmlstr);
             ELSE
                SELECT SUBSTR (l_result, l_retrieved + 1, l_offset)
                  INTO l_xmlstr
                  FROM DUAL;
                l_retrieved := l_retrieved + l_offset;
                fnd_file.put_line (fnd_file.output, l_xmlstr);
             END IF;
         END LOOP;
    3) In the example it is not explained how the concurrent program gets the xml data?
       I assume it is written to a file using the following line of code:
        fnd_file.put_line (fnd_file.output, l_xmlstr);
       I would appreciate if anyone can throw some light into my above queries so that I can understand the process clearly.
    Thanks & Regards
    Hawker

    Hi 32000 in the code is a 'safe' size smaller than the max available 32767, the loops purpose is to move through the entire thing in chunks that will be manageable in the limits of the data type.
    Btw; if you are in Oracle e-business suite then you can also use Oracle reports very simply to create XML output.
    If you have reports developer all you need to do is put raw sql (without any 'artifice' to create XML) in the report SQL and then set the reports output to XML in the program definition in Oracle e-business.
    best regards,
    Robert.

  • How to generate XML Publisher report from PLSQL Stored Procedure in APPS

    Hi,
    I have concurrent program of type PLSQL Stored procedure.I need to generate XML Publisher report from the same.I have changed the output of the concurrent program as "XML" but when I tried running it,the XML tags are not generated.Due to this I am unable to create the template.Its a urgent issue.
    Please help me out .
    Thanks in advance.
    Kaveri

    Hi Kaveri
    Sadly there is nothing magic about that output field. The only program type that you can flip it to XML and then magically get XML is for Oracle Reports. For plsql you will need to recode the plsql to generate XML rather than text that you have now.
    You have some options, best option first:
    1. Move the sql to a data template - check the user guide and blog for help or
    2. Use SQL XML or XMLGEN (not great for large datasets) or
    3. Use dbms_output.put_line and write the XML file manually - not performant at all
    Regards, Tim

  • Calling unix shell script from oracle stored procedure.. urgent!!!!!!!!!!!!

    Hi,
    i havea requirement where in i should be able to call my shell script through oracle stored procedure.i tried the following way..but iam unable to get the result.please find the details below.
    new.sh - my shell script - lctfile (LCTFILE) is the input pa
    v_config_file=`find $FND_TOP -name LCTFILE
    FNDLOAD apps/s0ccer@$dxbs1 0 Y DOWNLOAD $v_config_file /home/bir4163/RPT33/bin/menu.ldt MENU MENU_NAME='AR_NAVIGATE_GUI'
    if [ $? != 0 ];then
    echo "$DATE $0 FNDLOAD DOWNLOAD Failed!" | tee -a $LOG_FILE
    else
    echo "SUCCESS" | tee -a $LOG_FILE
    fi
    CREATE OR REPLACE PROCEDURE test_dbms_scheduler
    AS
    v_text VARCHAR2 (255) := 'AR_NAVIGATE_GUI';
    BEGIN
    DBMS_OUTPUT.put_line ('I am in Procedure');
    DBMS_SCHEDULER.create_job (
    job_name => 'test_dbms_scheduler',
    job_action => '/home/bir4163/RPT33/bin/new.sh',
    number_of_arguments => 1,
    job_type => 'executable',
    start_date => SYSDATE,
    repeat_interval => 'FREQ=SECONDLY; INTERVAL=1',
    enabled => FALSE,
    auto_drop => FALSE,
    comments => 'run shell script'
    DBMS_SCHEDULER.set_job_argument_value (job_name => 'test_dbms_scheduler',
    argument_position => 1,
    argument_value => v_text);
    DBMS_SCHEDULER.enable ('test_dbms_scheduler');
    DBMS_OUTPUT.put_line ('I am back in Procedure');
    EXCEPTION
    WHEN OTHERS
    THEN
    DBMS_OUTPUT.put_line (SQLCODE || SQLERRM);
    END;
    But iam unable to test it as i do not have permissions to access dbms_scheduler.can anybody tell me how to solve this using DBMS_PIPE with a sample code.
    please do help its very urgent
    thanks
    ramya

    Hi,
    Register your Shell Script as a concurrent program, Executable execution method "Host", then use fnd_request.submit_request to submit the program.
    Regards,
    Andries

  • Best practice for calling stored procedures as target

    The scenario is this:
    1) Source is from a file or oracle table
    2) Target will always be oracle pl/sql stored procedures which do the insert or update (APIs).
    3) Each failure from the stored procedure must log an error so the user can re-submit the corrected file for those error records
    There is no option to create an E$ table, since there is no control option for the flow around procedures.
    Is there a best practice around moving data into Oracle via procedures? In Oracle EBS, many of the interfaces are pure stored procs and not batch interface tables. I am concerned that I must build dozens of custom error tables around these apis. Then it feels like it would be easier to just write pl/sql batch jobs and schedule with concurrent manager in EBS (skip ODI completely). In that case, one could write to the concurrent manager log and the user could view the errors and correct.
    I can get a simple procedure to work in ODI where the source is the SQL, and the target is the pl/sql call to the stored proc in the database. It loops through every row in the sql source and calls the pl/sql code.
    But I can not see how to set which rows have failed and which table would log errors to begin with.
    Thank you,
    Erik

    Hi Erik,
    Please, take a look in these posts:
    http://odiexperts.com/?p=666
    http://odiexperts.com/?p=742
    They could help you in a way to solve your problem.
    I already used it to call Oracle EBS API's and worked pretty well.
    I believe that an IKM could be build to automate all the work but I never stopped to try...
    Does it help you?
    Cezar Santos
    http://odiexperts.com

  • Scheduling stored procedure using DBMS_JOB package

    I have stored procedure called “extract_every_day”, I want this procedure to run automatically at 7:00 PM every day.
    I used DBMS_JOB.SUBMIT to achieve this, below is pl/sql block
    DECLARE
    v_jobno number ;
    BEGIN
    DBMS_JOB.SUBMIT
    (v_jobno,
    ' extract_every_day ',
    TRUNC (SYSDATE) + 1 + 9/24,
    'TRUNC (SYSDATE) + 1 + 9/24');
    COMMIT;
    END;
    When I run above pl/sql block is that mean procedure “extract_every_day” executes every day and what is the significance of “job” OUT parameter in “DBMS_JOB.SUBMIT “ procedure. Also how can I see list of jobs submitted.
    Any help is appreciated.
    Thanks

    The OUT parameter is the unique number of the job being executed. This is the Sequence generated from sequence sys.jobseq
    Also, in the example you have provided, the Job will run at 9Am and not 7PM.
    To make it run at 7PM every day change the following lines :
    'TRUNC (SYSDATE) + 1 + 9/24'
    'TRUNC (SYSDATE) + 1 + 9/24'
    To ,
    'TRUNC (SYSDATE) + 19/24' <-- Changed
    'TRUNC (SYSDATE) + 1 + 19/24' <-- Changed
    Also do remember to include the parameter "job_queue_processes" parameter within the init.ora file. This parameter is used to determine the max no
    of concurrently running jobs (i.e. Set in Init.ora).
    NOTE :- Job_queue_process cannot be set to 0. If set to 0, no jobs is run.
    he view dba_jobs and dba_jobs_running should be used to view the jobs.
    -- Shailender Mehta --

  • How to run stored procedure in DOS command line????

    Hi,
    I want to run a stored procedure in DOS command line?
    (My_Stored_Procedure is the stored procedure that I want to run )
    This is what I did in DOS prompt
    C:\>sqlplus scott/tiger exec lMy_Stored_Procedure <Return>
    Obviously it is NOT working. Please send me the correct way to fix this.
    Thanks so much in advance for helping.
    Cuong

    Billy  Verreynne  wrote:
    BluShadow wrote:
    True Billy, but even Windows hasn't completely got away from using the "DOS" word...Yeah - the command line/shell environment is based on that of the old DOS command interpreter. But Microsoft does not make the mistake of call it DOS.
    In fact, with earlier versions of Windows NT, a 16bit DOS real-mode virtual machine was supported. This was very kewl.
    Running a large BBS with multiple nodes back then required a DOS machine per node, an IPX network, and a Novell file server.Novell Netwars. ;)
    Ahhhh! good old DOS... so many good programs written at that low level, outside the Windoze environment.Yeah.. cut my teeth on writing code for DOS. Still have all my old BIOS and assembler manuals for it. Wrote my own screen s/w (write to a buffer and then move it into the video buffer, instead of writing char wise to the video buffer via interrupts), mucking about with my own concurrent threading model (using very simplistic cooperative multitasking) and so on. Heck, wrote tons of s/w on DOS... :-)Yeah I've still got a copy of my old machine code programs for writing to buffers and screen memory switching for smooth animation. Run them nowadays and they run like sh!t off a shovel. And all my old coursework including writing an interpreted language and multi-window (dos based windows) editor, parser and the code to execute the language and display the output. Oooo, and so much other stuff.
    Awesome back then as you got really intimate with the o/s and hardware. This is sorely lacking today in environments like Java. And I think the reason why so much code written today is less than optimal - to put it kindly.Exactly. Started for me on the Sinclair zx81 (writing Basic), then the Sinclair Spectrum (Basic and Assembly), then Sinclair QL (yes I really had one!) and then the BBC Master 128K (where I got to writing my own rom filing system and creating my own eproms, to integrate with the word processor for additional printing features etc. as well as storing games on rom for speedy loading - and I still have it and it still works!)
    It's that level of working with the underlying memory and assembly language that gives you the understanding of how values are passed between code using the stack and registers, and how memory allocation and referencing is done etc. As you say... it's missed in a lot of todays teaching, which just seems too high level and misses the basic concepts of things such as datatypes and why they are different. I bet half the modern programmers wouldn't have a clue how to do multiplication or division of binary numbers using the carry flag.

  • How to write stored procedure to spool data into file

    Hi ,
    We get differnt excel sheets of differnt products.
    We upload data from excel sheet to database . After uploading data , I run Preprossor (sql script) to check the data
    This preprocessor script contains several select statements that query different tables in database .the output is spooled into a cvs file .
    I need to change this script into a stored procedure and spool the output to cvs file.
    File spooling should be done inside the stored procedure so that if I call this stored procedure from java program ,or any concurrent program,its output is .cvs file and in parameter should be productname.
    But inside the stored procedure , we cannot spool the data to some .cvs file . Is any way.I do not want to spool to file when calling.It should be inside stored procedure.
    Or do I need to create a table and insert all the select statements output into it .
    Here is the sample preprocessor script.
    spool Graco_Product.csv
    set head off
    set feedback off
    set Pagesize 100
    SELECT '1. EVERY ASSEMBLY GROUP ADDED IN sys_PRODUCT TABLE MUST HAVE AT LEAST ONE ITEM IN WOC_ASSEMBLY_ITEM'
         FROM DUAL;
    SELECT 'ASSEMBLY_GROUP_NAME'
         FROM DUAL;
    SELECT
         assembly_group_name
         FROM association
         WHERE product_model_name = 'Graco_Product'
         AND assembly_group_name NOT IN (SELECT DISTINCT assembly_group_name FROM woc_assembly_item);
    SELECT '2. A RULE SHOULD HAVE AT LEAST ONE EXPRESSION FOR ITS ACTION SIDE.'
         FROM DUAL;
    SELECT 'RELATION_ID , RELATION_TYPE'
         FROM DUAL;
    SELECT wr.Relation_ID                    ||','||
         wr.Relation_Type                    
         FROM WOC_Relation wr
         WHERE NOT EXISTS (SELECT 'X' FROM WOC_Relation_Expression wre
    WHERE wre.Relation_Side = 'Action'
    AND wr.Relation_ID = wre.Relation_ID)
         AND wr.Relation_Type NOT IN ( 'Rule Warning','Rule Resource','Rule Default');
    SELECT '3. PROPERTIES USED IN RULES SHOULD EXIST IN WOC_PROPERTY_MASTER -- EXP_LHS_VALUE'
         FROM DUAL;
    SELECT
         'RELATION_OWNER,EXP_LHS_OPERAND,RELATION_SIDE,RELATION_ID,EXP_LHS_VALUE,RELATION_TYPE'     
         FROM DUAL;
    SELECT
         b.relation_owner               ||','||
         a.exp_lhs_operand               ||','||
         a.relation_side                    ||','||
         a.relation_id                    ||','||
         a.exp_lhs_value                    ||','||
         b.relation_type
         FROM woc_relation_expression a, woc_relation b
         WHERE a.exp_lhs_value IS NOT NULL
         AND a.exp_lhs_value_type = 'Property'
         AND a.exp_lhs_value NOT IN (SELECT property_name FROM woc_property)
         AND b.product_model_name = 'Graco_Product'
         AND a.relation_id = b.relation_id;
    SELECT '--------------------------------------------------------------------------------'
    from dual;
    spool off
    set head on
    set feedback on

    High level description
    Full documentation
    Note that the UTL_ and DBMS_ packages are all covered in the PL/SQL Packages and Types Reference.
    You may also want to read up on the CREATE DIRECTORY statement, which lets you refer to an actual OS directory (which you create separately) via a database object.

  • Help in stored procedure

    i have a stored procedure in MSSQL which needs to be migrated to oracle 10g,i have got problem related to migration.
    My mssql stored procedure is like as follows:
    create procedure sample(
    var1 varchar(20),
    var2 varchar(20) )
    as
    declare @V_TBL table(col1 varchar(20), col2 varchar(20))
    begin
    insert into @V_TBL(col1,col2)
    select col1,col2 from table1 where col1=@var1 and col2=@var2
    some more logic
    end
    now in oracle how do i create this variable table or some other way is there to solve this?

    > i have got problem related to migration.
    Yep.. and this is to be expected. Why? Because Oracle is different than SQL-Server. And it is because of these differences that the market buys Oracle. Not because Oracle is the same as SQL-Server, but because it is difference.
    The first thing you need to accept that migration is not going to be easy and painless - because of these differences.
    What works and works well in SQL-Server, can spell a performance disaster in Oracle. And vice versa.
    Why are temp tables typically used in SQL-Server and Sybase and Ingres and others? Because these databases have a different concurrency and isolation model than Oracle.
    In these products, Writers can block Readers and Readers can block Writers.
    In Oracle, a Reader will never block a Writer. A Writer will never block a Reader. One Writer will only ever block another Writer when vying for the same row. (and on a very rare occasion, when vying for the same data block that lacks sufficient transaction slots)
    Simple example. I open a cursor [SELECT * FROM emp]. I fetch 10 rows of a 100 rows. You start a transaction. You issue a [DELETE FROM emp] and commit. The EMP table is now empty. I fetch the next set of 10 rows using my cursor. What do I see?
    I see the next 10 rows as the EMP table looked like at the time I opened my cursor. I still see all 100 rows. Because that was The Truth at the time I opened my cursor. Oracle guarantees me a consistent read. No dirty reads.
    So the "tricks" you pulled in SQL-Server to work around the reader and writer blocking issue (a failure of SQL-Server ito providing read consistency), is not applicable in Oracle. And the reasons and methods for using temp tables in SQL-Server is not valid in Oracle.
    So when migrating SQL-Server stored proc code to Oracle.. it is a migration. Which means refactoring design and code. Do not expect to be able to simply port the design or code.

  • Locking in EntityFramework - calling empty stored procedure releases lock acquired using sp_getapplock

    I have a patient table in the SQL Server database. Clients connect to the database and checkout one of the patients and do some operations on it and save it afterwards.
    Since multiple clients might access the patient at the same time. I wanted to implement pessimistic locking mechanism, So that if one client can acquire a lock to a particular patient at a time.
    Also if one of the clients locks a particular patient and either crashes or closes the client application the lock should be released. In case of crash the lock should be released when we detect that the connection of client with the database is closed.
    I found out that I could use sp_getapplock and sp_releaseapplock to
    do achieve this and specify @LockOwner
    = 'Session' when calling sp_getapplock,
    this ensures that the lock is released once the database session with the client closes.
    From the code, I call a stored procedure in database to acquire the lock. This acquires the lock correctly and if i close off the client app or the client app crashes the lock is released. This is behaving as I wanted it to.
    The problem happens when I call another stored procedure which is supposed to release the lock. As soon as the stored procedure is entered the lock is released, before we even execute sp_releaseapplock
    @patientId, @LockOwner = 'Session' the line which is actually supposed to release the lock.
    I tried creating an empty stored procedure (just commented out
    DECLARE @result int
    EXEC @result = sp_releaseapplock @patientId, @LockOwner = 'Session'
    This stored procedure still releases the lock I acquired using sp_getapplock.
    I can't seem to understand why this is happening. It should only release when I explicitly call `sp_releaseapplock @patientId, @LockOwner = 'Session'``
    CREATE PROCEDURE [dbo].[uspReleaseAppLock]
    @patientId nvarchar(max), -- Patient ID
    @ReturnValue int Output
    AS
    BEGIN
    DECLARE @result int
    EXEC @result = sp_releaseapplock @patientId, @LockOwner = 'Session'
    SET @ReturnValue = @@SPID
    END
    Could someone tell me why this is happening. What am I missing here ? I checked that the session ids of both the stored procedures (for acquiring and releasing the lock) are same, so it dose not seem that a new session is being created by entity frame work
    for each call to the stored procedure. Something else is going on which I am not able to comprehend. Any ideas ?

    Hi oalvi,
    The Stored Procedure(SP) sp_getApplock initialed with "@LockOwner='Session'" is
    session scoped. Your procedure
    [dbo].[uspReleaseAppLock]
    did the same work as you explicitly call "sp_releaseapplock @Resource = @patientId, @LockOwner='Session'", after the SP
    uspReleaseAppLock
    called or the current session ends, the lock released.
    It doesn't make sense to call the uspReleaseAppLock to release the lock initialized in another session. If you try, you get the error like below, as I mentioned, the lock is session scoped.
    "Cannot release the application lock (Database Principal: 'public', Resource: 'patient1') because it is not currently
    held"
    Regarding the same session ID you get from calling 2 SPs separately in Entity Framework(EF). As per my limitation knowledge on EF, If the maxsize of the project connection
    pool equals 1, you may get the same session always.
    Some cautions for sp_getApplock
    Locks can be explicitly released with sp_releaseapplock. When an application calls sp_getapplock multiple times for the same lock resource, sp_releaseapplock must be called the same number of times to release the lock.
    Due to the connection pool, the sessions may last long, that's what you need to take into account.
    By the way, is there any reason that you have to use the sp_getApplock? What is the procedure doing that you cannot rely on SQL Servers build-in concurrency control mechanisms?
    If you have any question, feel free to let me know.
    Eric Zhang
    TechNet Community Support

  • Get variable values from a stored procedure

    I am using SQL 2008R2 and I want to replace a view inside a stored procedure with a new stored procedure to return multiple variable values. Currently I am using the code below to get values for 4 different variables.  I would rather get the 4 variables
    from a stored procedure (which returns all of these 4 values and more) but not sure how to do so.  Below is the code for getting the 4 variable values in my current sp.
    DECLARE @TotalCarb real;
    DECLARE @TotalPro real;
    DECLARE @TotalFat real;
    DECLARE @TotalLiquid real;
    SELECT @TotalCarb = ISNULL(TotCarb,0),
    @TotalPro = ISNULL(TotPro,0),
    @TotalFat = ISNULL(TotFat,0),
    @TotalLiquid = ISNULL(TotLiq,0)
    FROM dbo.vw_ActualFoodTotals
    WHERE (MealID = @MealID);

    You can replace the view with inline table valued user-defined function:
    http://www.sqlusa.com/bestpractices/training/scripts/userdefinedfunction/
    See example: SQL create  INLINE table-valued function like a parametrized view
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Design & Programming
    New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012

  • Pointbase : How can I create a stored procedure with Pointbase database?

    Hello,
    Excuse me for my english, I'm not anglophone. I try to create a stored procedure.
    This is my file SampleExternalMethods.java :
      import java.sql.*;    //import com.pointbase.jdbc.jdbcInOutDoubleWrapper;          public class SampleExternalMethods    {      // A connection object to allow database callback      static Connection conn = null;      static Statement l_stmt;      static Statement m_stmt;      static CallableStatement m_callStmt = null;      static ResultSet l_rs = null;          public static void main(String[] args)      {        try        {          String url = "jdbc:pointbase:server://localhost/pointbaseDB";          String username = "PBPUBLIC";          String password = "PBPUBLIC";          conn = DriverManager.getConnection(url, username, password);          doCreateProcedure();          doInvokeProcedure();        } catch (SQLException e) {          e.printStackTrace();        } finally {          if (m_stmt != null) {            try {              m_stmt.close();            } catch (Exception e) {              e.printStackTrace();            }          }          if (m_callStmt != null) {            try {              m_callStmt.close();            } catch (Exception e) {              e.printStackTrace();            }          }          if (conn != null) {            try {              conn.close();            } catch (Exception e) {              e.printStackTrace();            }          }        }      }                  public static void getCountry(String Iso_Code)      {        try        {          // Query the database for the country iso code          l_stmt = conn.createStatement();          l_rs = l_stmt.executeQuery( "SELECT * FROM countries"          + " WHERE country_iso_code ='" + Iso_Code + "'");          //Affichage du résultat de la requête          l_rs.next();          System.out.print(l_rs.getString(1) + " - ");          System.out.print(l_rs.getString(2) + " - ");          System.out.println(l_rs.getString(3));          // Close the result set          l_rs.close();        } catch (SQLException e) {          e.printStackTrace();        } finally {          if (l_rs != null) {            try {              l_rs.close();            } catch (Exception e) {              e.printStackTrace();            }          }          if (l_stmt != null) {            try {              l_stmt.close();            } catch (Exception e) {              e.printStackTrace();            }          }        }      }            public static void doCreateProcedure() throws SQLException {        // SQL statement to create a stored procedure        String SQL_CREATE_PROC = "CREATE PROCEDURE getCountry(IN P1 VARCHAR(30))"        + " LANGUAGE JAVA"        + " SPECIFIC getCountry"        + " NO SQL"        + " EXTERNAL NAME \"SampleExternalMethods::getCountry\""        + " PARAMETER STYLE SQL";        // Create a SQL statement        m_stmt = conn.createStatement();        // Execute the SQL        m_stmt.executeUpdate(SQL_CREATE_PROC);        // Close the statement        //m_stmt.close();      }          public static void doInvokeProcedure() throws SQLException {        // Create SQL to invoke stored procedures        String SQL_USE_PROC = "{ call getCountry(?) }";        // Create a callable statement with three binding parameters        m_callStmt = conn.prepareCall(SQL_USE_PROC);        m_callStmt.setString(1, "CA");        m_callStmt.executeQuery();        // Close the callable statement        //m_callStmt.close();      }    } 
    Afterwards, I have read this note in a Pointbase document:
    To invoke the dateConvert external Java method from a stored function, you must use the
    CREATE FUNCTION statement. The dateConvert external Java method is called from the
    class, SampleExternalMethods.
    In order for the database to access this external Java method, the class SampleExternalMethods
    must be included in the database CLASSPATH. For PointBase Embedded - Server Option, it
    must be in the Server CLASSPATH, but not in the Client CLASSPATH.
    If PointBase Server is run with the Java Security Manager, in the java policy file grant
    ’com.pointbase.sp.spPermission’ to the class that implements the external Java method.
    An "spPermission" consists of a class name with no action. The class name is a name of a class
    that could be used in creating a Stored Procedure in PointBase. The naming convention follows
    the hierarchical property naming convention and that is supported by
    "java.security.BasicPermission". An asterisk may appear by itself, or if immediately preceded
    by ".", may appear at the end of the name, to signify a wildcard match. The name cannot
    contain any white spaces.
    I'm not sure, but I suppose that I must include the class SampleExternalMethods in a .jar file.
    The database CLASSPATH could be : C:\Sun\AppServer\pointbase\lib\
    These my files in this database CLASSPATH:
    pbclient.jar
    pbembedded.jar
    pbtools.jar
    pbupgrade.jar
    I have tryed to include the class SampleExternalMethods in pbclient.jar and pbembedded.jar with this command:
    jar -uf pbembedded.jar SampleExternalMethods
    Afterwards I do that,
    1) Start Pointbase
    2) Configuration of classpath
    set classpath=C:\Sun\AppServer\pointbase\lib\pbclient.jar
    set classpath=%classpath%;D:\J2EE\Ch07Code\Ch07_06
    I precise that my file SampleExternalMethods is into D:\J2EE\Ch07Code\Ch07_06\Ch07.
    Then, I run the program:
    D:\J2EE\Ch07Code\Ch07_06>java -Djdbc.drivers=com.pointbase.jdbc.jdbcUniversalDriver Ch07.SampleExternalMethods
    But I have an error message:
    Exception in thread "main" java.lang.NoClassDefFoundError: Ch07.SampleExternalMethods (wrong name: SampleExternalMethods)
    at java.lang.ClassLoader.defineClass0(Native Method)
    at java.lang.ClassLoader.DefineClass(ClassLoader.java:539)
    The problem, I suppose, comes from that the class SampleExternalMethods
    must be included in the database CLASSPATH, but there is a pbserver.jar with pointbase normally, but I didn't find it. That's why I use pbembedded.jar or pbclient.jar in order to include the class SampleExternalMethods. May be I must start from C:\Sun\AppServer\pointbase\lib\ instead of D:\J2EE\Ch07Code\Ch07_06\Ch07?
    Please, can somebody helps me?
    Thank you in advance.
    cagou!

    jschell wrote:
    And I doubt you can recurse like that for embedded java. You must have a class that does the functionality and another class that creates the proc.
    >And I doubt you can recurse like that for embedded java. You must have a class that does the functionality and another class that creates the proc.
    >
    And I doubt you can recurse like that for embedded java. You must have a class that does the functionality and another class that creates the proc.
    Thank you for your response, I have done two classes:
    SampleExternalMethods.java:
    package Ch07;
    import java.sql.*;*
    *public class SampleExternalMethods*
    *public static void getCountry(String Iso_Code)*
    *// A connection object to allow database callback*
    *Connection l_conn = null;*
    *Statement l_stmt = null;*
    *ResultSet l_rs = null;*
    *try*
    *String url = "jdbc:pointbase:server://localhost/pointbaseDB";*
    *String username = "PBPUBLIC";*
    *String password = "PBPUBLIC";*
    *l_conn = DriverManager.getConnection(url, username, password);*
    *// Query the database for the country iso code*
    *l_stmt = l_conn.createStatement();*
    *l_rs = l_stmt.executeQuery( "SELECT* FROM PBPUBLIC.COUNTRIES"
    +" WHERE country_iso_code ='"+ Iso_Code +"'");+
    +//Affichage du r&eacute;sultat de la requ&ecirc;te+
    +l_rs.next();+
    +System.out.print(l_rs.getString(1)+ " - ");
    System.out.print(l_rs.getString(2) +" - ");+
    +System.out.println(l_rs.getString(3));+
    +// Close the result set+
    +l_rs.close();+
    +} catch (SQLException e) {+
    +e.printStackTrace();+
    +} finally {+
    +if (l_rs != null) {+
    +try {+
    +l_rs.close();+
    +} catch (Exception e) {+
    +e.printStackTrace();+
    +}+
    +}+
    +if (l_stmt != null) {+
    +try {+
    +l_stmt.close();+
    +} catch (Exception e) {+
    +e.printStackTrace();+
    +}+
    +}+
    +if (l_conn != null) {+
    +try {+
    +l_conn.close();+
    +} catch (Exception e) {+
    +e.printStackTrace();+
    +}+
    +}+
    +}+
    +}+
    +}+
    CreateMethods.java:
    +package Ch07;+
    +import java.sql.*;+
    +public class CreateMethods+
    +{+
    +// A connection object to allow database callback+
    +static Connection m_conn = null;+
    +static Statement m_stmt;+
    +static CallableStatement m_callStmt = null;+
    +public static void main(String[] args)+
    +{+
    +try+
    +{+
    +String url = "jdbc:pointbase:server://localhost/pointbaseDB";+
    +String username = "PBPUBLIC";+
    +String password = "PBPUBLIC";+
    +m_conn = DriverManager.getConnection(url, username, password);+
    +doCreateProcedure();+
    +doInvokeProcedure();+
    +} catch (SQLException e) {+
    +e.printStackTrace();+
    +} finally {+
    +if (m_stmt != null) {+
    +try {+
    +m_stmt.close();+
    +} catch (Exception e) {+
    +e.printStackTrace();+
    +}+
    +}+
    +if (m_callStmt != null) {+
    +try {+
    +m_callStmt.close();+
    +} catch (Exception e) {+
    +e.printStackTrace();+
    +}+
    +}+
    +if (m_conn != null) {+
    +try {+
    +m_conn.close();+
    +} catch (Exception e) {+
    +e.printStackTrace();+
    +}+
    +}+
    +}+
    +}+
    +public static void doCreateProcedure() throws SQLException {+
    +// SQL statement to create a stored procedure+
    +String SQL_CREATE_PROC = "CREATE PROCEDURE PBPUBLIC.getCountry(IN P1 VARCHAR(30))"+
    " LANGUAGE JAVA"
    +" SPECIFIC getCountry"+
    " NO SQL"
    +" EXTERNAL NAME \"SampleExternalMethods::getCountry\""+
    " PARAMETER STYLE SQL";
    // Create a SQL statement
    m_stmt = m_conn.createStatement();
    // Execute the SQL
    m_stmt.executeUpdate(SQL_CREATE_PROC);
    // Close the statement
    //m_stmt.close();
    public static void doInvokeProcedure() throws SQLException {
    // Create SQL to invoke stored procedures
    String SQL_USE_PROC = "{ call getCountry(?) }";
    // Create a callable statement with three binding parameters
    m_callStmt = m_conn.prepareCall(SQL_USE_PROC);
    m_callStmt.setString(2, "CA");
    m_callStmt.executeQuery();
    // Close the callable statement
    //m_callStmt.close();
    }But I have the same error message that previously.
    I have read this note and I suppose that the problem is linked:
    If PointBase Server is run with the Java Security Manager, in the java policy file grant
    *’com.pointbase.sp.spPermission’ to the class that implements the external Java method.*
    An "spPermission" consists of a class name with no action. The class name is a name of a class
    that could be used in creating a Stored Procedure in PointBase. The naming convention follows
    the hierarchical property naming convention and that is supported by
    *"java.security.BasicPermission". An asterisk may appear by itself, or if immediately preceded*
    by ".", may appear at the end of the name, to signify a wildcard match. The name cannot
    contain any white spaces.
    Can you explain me what I must to do in order to solve this problem of spPermission.
    Thanks.

Maybe you are looking for