Update stored procedure syntax

Can someone post an example of a stored procedure that is used to update a row in a table with a primary key.... thought it would be easy enough to find an eg on google but no luck so far.
Cheers

Hey if you dont have the Primay Key or Any other key
then for updating the table records, always use the
Rowid "ABC" in you select statements ie in the Cursor
and then alsways use that RowId in your update
statements.
It will work fast & 100% correct also.!!!!I would have thought the statement:
Can someone post an example of a stored procedure that is used to update a row in a table with a primary key
would be good indication that it has a primary key.
And if you're talking about updating rows from a cursor then surely it would be easier to use a CURSOR ... FOR UPDATE statment and then UPDATE ... WHERE CURRENT ... to update the current row. Why the need for using ROWID's?

Similar Messages

  • MySQL Stored Procedure Syntax Errors

    I have an online application I would like to use transactions to either commit all db updates or none at all. The code I have created is as follows, not only am I getting a syntax error on lines 5 and 16, but quite frankly I am unsure the code will actually do what I want. Please let me know if you see the syntax errors and could explain them to me.
    CREATE PROCEDURE increase_maint_priority
        (maint_item INT, new_priority INT, cur_priority INT, center_id INT)
    BEGIN
        START TRANSACTION; -- line 5 syntax error
        -- start updates
        UPDATE maintitem SET priority = (priority+1)
            WHERE priority > cur_priority
            AND priority <= new_priority
            AND centerID = center_id;
        UPDATE maintitem SET priority = new_priority
            WHERE id = maint_item;
        COMMIT;
    END; -- line 16 syntax error
    Thank you in advance for helping a newb to stored procedures.
    If you would like to help me figure out if this code will actually work for what I want the following describes the situation.
    Main idea: business location managers submit requests for maintenance at their center. Requests can be added anywhere in the priority list (1=highest priority). They can also change the priority of a request at any time.
    Previously I have been using php to control a loop of mysql update queries (yikes, I know now, 2 sql statements could do the trick) and lately we have been experiencing duplicate priorities, and other problems that seem to be most likely linked to the updating of priorities of multiple items.
    Ex: moving priority item 6 to priority 1 requires 1 update query for the current 6th priority item, but a second query (or loop of several more since I was very new to sql statements at time of development 2 years ago) to update the other priorities.
    Thus the desire for the transaction method.
    Again, thanks in advance for any help on this issue.
    P.S. - I am using MySQL workbench to write this and that's where I get the errors.

    Yes, of course.
    DELIMITER //
    CREATE PROCEDURE increase_maint_priority
        (maint_item INT, new_priority INT, cur_priority INT, center_id INT)
    BEGIN
        START TRANSACTION;
        -- start updates
        UPDATE maintitem SET priority = (priority+1)
            WHERE priority > cur_priority
            AND priority <= new_priority
            AND centerID = center_id;
        UPDATE maintitem SET priority = new_priority
            WHERE id = maint_item;
        COMMIT;
    END //
    DELIMITER ;
    Just so you're aware, the table name is actually in a slightly dfferent format: `db_name`.`table_name` I have just renamed it for privacy purposes.

  • Stored Procedure syntax error

    I'm trying to create a stored procedure that does not have any IN or OUT parameters. It gives syntax errors:
    create or replace
    procedure GEN_NEW_DATA
    as
    cursor for_msgid is select PARENTID from WORKITEM;
    msgid_rec for_msgid%rowtype;
    begin
    for msgid_rec in for_msgid loop
    update FIELDTYPE set FIELDVALUE= (select ACCOUNTID from ACCOUNT where ACCOUNTNAME= (select FIELdVALUE from FIELDTYPE where FIELDNAME= msgid_rec.PARENTID || 'xAgency' ) ) where FIELDNAME= msgid_rec.PARENTID || 'xAgency';
    commit;
    end loop;
    dbms_output.put_line('Done');
    end;
    Can someone help me with the syntax here.

    msgid_rec for_msgid%rowtype;I think this is not allowed..
    ----Try this
    create or replace
    procedure GEN_NEW_DATA
    as
    cursor for_msgid is select PARENTID from WORKITEM;
    --msgid_rec for_msgid%rowtype;
    begin
    for msgid_rec in for_msgid loop
    update FIELDTYPE set FIELDVALUE= (select ACCOUNTID from ACCOUNT where ACCOUNTNAME= (select FIELdVALUE from FIELDTYPE where FIELDNAME= msgid_rec.PARENTID || 'xAgency' ) ) where FIELDNAME= msgid_rec.PARENTID || 'xAgency';
    commit;
    end loop;
    dbms_output.put_line('Done');
    end;
    Message was edited by:
            jeneesh                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • SQL Server Service Broker Updating Stored procedure

    how can you update the service broker stored procedure. when i update the stored procedure the changes dont come into affect. i have tried to alter the queue, waited for all jobs to finish, but some how still the old stored procedure is running. is there any
    way i can force changes to the stored procedure.
    i have tried sql profiler tracing but that didnt show any changes.
    I cannot alter the service broker stored procedure, when I update the stored procedure it does not show any error and successfully gets updated but the changes does not come into affect.
    Is it because I need to stop the queue of the service broker on both databases before the changes could come into affect?
    Note: the service broker stored procedures produce and read xmls.

    Presumably, this is because the procedure is executing when you alter the procedure. And if the procedure never exits, the old code will keep on running. One way to address this is to have the procedure to return if a new message has not been picked up in,
    say, 1000 milliseconds.
    Here is a repro to shows what I'm talking about.
    ------------------------------- Service Broker Objects ------------------------------------------
    CREATE MESSAGE TYPE OrderRequest VALIDATION = NONE
    CREATE MESSAGE TYPE OrderResponse VALIDATION = NONE
    go
    CREATE CONTRACT OrderContract
       (OrderRequest SENT BY INITIATOR,
        OrderResponse SENT BY TARGET)
    go
    CREATE QUEUE OrderRequests WITH STATUS = OFF
    CREATE QUEUE OrderResponses WITH STATUS = ON
    go
    CREATE SERVICE OrderRequests ON QUEUE OrderRequests (OrderContract)
    CREATE SERVICE OrderResponses ON QUEUE OrderResponses (OrderContract)
    go
    -- Procedure to send a message and receive a response.
    CREATE PROCEDURE send_and_get_answer AS
    DECLARE @handle uniqueidentifier,
             @binary varbinary(MAX)
          SELECT @binary = CAST (N'Kilroy was here' AS varbinary(MAX))
          BEGIN DIALOG CONVERSATION @handle
          FROM  SERVICE OrderResponses
          TO    SERVICE 'OrderRequests'
          ON    CONTRACT OrderContract
          WITH ENCRYPTION = OFF
          ;SEND ON CONVERSATION @handle
          MESSAGE TYPE OrderRequest (@binary)
       WAITFOR (RECEIVE TOP (1)
                         @handle = conversation_handle,
                         @binary = message_body
                FROM    OrderResponses)
       SELECT cast(@binary AS nvarchar(MAX)) AS response
       END CONVERSATION @handle
    go
    -- Procedure to process a message
    CREATE PROCEDURE ProcessOrders AS
    SET NOCOUNT, XACT_ABORT ON
    DECLARE @DialogHandle  uniqueidentifier,
            @MessageType   sysname,
            @binarydata    varbinary(MAX)
    -- Get next message of the queue.
    WAITFOR (
       RECEIVE TOP (1) @DialogHandle = conversation_handle,
                         @MessageType  = message_type_name,
                         @binarydata   = message_body
       FROM    OrderRequests
    SELECT @binarydata = CAST( reverse( CAST( @binarydata AS nvarchar(MAX) )) AS varbinary(MAX))
    ; SEND ON CONVERSATION @DialogHandle
    MESSAGE TYPE OrderResponse (@binarydata)
    END CONVERSATION @DialogHandle
    go       
    -- Make this an activaton procedure.
    ALTER QUEUE OrderRequests WITH
          STATUS = ON,
          ACTIVATION (STATUS = ON,
                      PROCEDURE_NAME = ProcessOrders,
                      MAX_QUEUE_READERS = 1,
                      EXECUTE AS OWNER)
    go
    -------------------------------- Send a message  -------------------------------------------
    EXEC send_and_get_answer
    go
    ------------------------ Change the procedure --------------------------------
    ALTER PROCEDURE ProcessOrders AS
    SET NOCOUNT, XACT_ABORT ON
    DECLARE @DialogHandle  uniqueidentifier,
            @MessageType   sysname,
            @binarydata    varbinary(MAX)
    -- Get next message of the queue.
    WAITFOR (
       RECEIVE TOP (1) @DialogHandle = conversation_handle,
                         @MessageType  = message_type_name,
                         @binarydata   = message_body
       FROM    OrderRequests
    SELECT @binarydata = CAST( upper( CAST( @binarydata AS nvarchar(MAX) )) AS varbinary(MAX))
    ; SEND ON CONVERSATION @DialogHandle
    MESSAGE TYPE OrderResponse (@binarydata)
    END CONVERSATION @DialogHandle
    go
    -------------------------------- Send new message -------------------------------------------
    EXEC send_and_get_answer    -- Still produces a message in reverse.
    EXEC send_and_get_answer    -- Now we get the expected result.
    go
    DROP SERVICE OrderRequests
    DROP SERVICE OrderResponses
    DROP QUEUE OrderRequests
    DROP QUEUE OrderResponses
    DROP PROCEDURE ProcessOrders
    DROP PROCEDURE send_and_get_answer
    DROP CONTRACT OrderContract
    DROP MESSAGE TYPE OrderRequest
    DROP MESSAGE TYPE OrderResponse
    go
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Stored Procedure Syntax

    Hi,
    I am new to Oracle and am trying to execute a stored procedure with parameters ..but I keep getting the error:
    ORA 00900- Invalid SQL Statement ....Below is the SQL statement.... I am able to run the SQL successfully on the SQL server with slight modifications .....I am using the Oracle SQL Developer tool...
    execute CARD_SUMMARY (212,"ALL","ALL","ALL","ALL","ALL","01/01/2010","01/01/2011");
    Please advice...
    Thank you,

    Here is the stored procedure :
    create or replace PROCEDURE "CARD_SUMMARY" ( rs out sys_refcursor,
    region_cd in varchar2,
    branch_cd in varchar2,
    state in varchar2,
    source_cd in varchar2,
    reason_cd in varchar2,
    start_date in varchar2,
    end_date in varchar2 )
    is
    v_region_cd varchar2(6);
    v_branch_cd varchar2(6);
    v_state varchar2(3);
    v_source_cd varchar2(6);
    v_reason_cd varchar2(6);
    v_start_date DATE := to_date(start_date,'mm/dd/yyyy');
    v_end_date DATE := to_date(end_date,'mm/dd/yyyy');
    BEGIN
    IF region_cd <> 'ALL' THEN
    v_region_cd := region_cd;
    END IF;
    IF branch_cd <> 'ALL' THEN
    v_branch_cd := branch_cd;
    END IF;
    IF state <> 'ALL' THEN
    v_state := state;
    END IF;
    IF source_cd <> 'ALL' THEN
    v_source_cd := source_cd;
    END IF;
    IF reason_cd <> 'ALL' THEN
    v_reason_cd := reason_cd;
    END IF;
    IF v_state = '1' THEN
    open rs FOR
    select br.branch_name as "branch",
    u.username as "username",
    Count(ch.source_cd)
    from credential_history ch,
    member mbr,
    membership ms,
    branch br,
    codes cd,
    iusers u,
    sales_agent sa
    where ch.waived_by = u.user_id
    and mbr.member_ky = ch.member_ky
    and u.user_id = sa.user_id
    and sa.user_id = ch.waived_by
    and sa.branch_ky = br.branch_ky
    and mbr.membership_ky = ms.membership_ky
    and ch.reason_cd in ('DUPC')
    and ch.reason_cd = cd.code
    and cd.code_type = 'DCREAS'
    and cd.code = nvl(v_reason_cd, cd.code)
    and br.branch_cd = nvl(v_branch_cd, br.branch_cd)
    and br.region_cd = nvl(v_region_cd, br.region_cd)
    and ch.source_cd = nvl(v_source_cd, ch.source_cd)
    and br.state not in ( 'PA' )
    and ch.card_req_dt between v_start_date and v_end_date
    group by br.branch_name, u.username, ch.source_cd
    order by br.branch_name, u.username, ch.source_cd;
    ELSE
    open rs FOR
    select br.branch_name as "branch",
    u.username as "username",
    Count(ch.source_cd)
    from credential_history ch,
    member mbr,
    membership ms,
    branch br,
    codes cd,
    iusers u,
    sales_agent sa
    where ch.waived_by = u.user_id
    and mbr.member_ky = ch.member_ky
    and u.user_id = sa.user_id
    and sa.user_id = ch.waived_by
    and sa.branch_ky = br.branch_ky
    and mbr.membership_ky = ms.membership_ky
    and ch.reason_cd in ('DUPC')
    and ch.reason_cd = cd.code
    and cd.code_type = 'DCREAS'
    and cd.code = nvl(v_reason_cd, cd.code)
    and br.branch_cd = nvl(v_branch_cd, br.branch_cd)
    and br.region_cd = nvl(v_region_cd, br.region_cd)
    and ch.source_cd = nvl(v_source_cd, ch.source_cd)
    and br.state = nvl(v_state, br.state)
    and ch.card_req_dt between v_start_date and v_end_date
    group by br.branch_name, u.username, ch.source_cd
    order by br.branch_name, u.username, ch.source_cd;
    END IF;
    END CARD_SUMMARY;
    The statements that I have tried are :
    CALL CARD_SUMMARY('ALL','ALL','ALL','ALL','ALL',DATE '2010-01-01',DATE '2011-01-01'); ----This throws wrong number or types of argument error...
    BEGIN
    CARD_SUMMARY('ALL','ALL','ALL','ALL','ALL',DATE '2010-01-01',DATE '2011-01-01'); ---------This throws wrong number or types of argument error...
    END;

  • Forms9i, data block based on stored procedures, refresh on update ?

    Hi,
    I am using
    Forms [32 Bit] Version 9.0.2.9.0 (Production)
    Oracle9i Enterprise Edition Release 9.2.0.5.0 - 64bit Production
         With the Partitioning, OLAP and Oracle Data Mining options
         JServer Release 9.2.0.5.0 - Production
    Oracle Toolkit Version 9.0.4.0.23 (Production)
    PL/SQL Version 9.0.1.3.1 (Production)
    Oracle Procedure Builder V9.0.2.0.7 Build #1022 - Production
    PL/SQL Editor (c) WinMain Software (www.winmain.com), v1.0 (Production)
    Oracle Query Builder 9.0.2.0.0 - Production
    Oracle Virtual Graphics System Version 9.0.1.5.0 (Production)
    Oracle Tools GUI Utilities Version 9.0.4.0.9 (Production)
    Oracle Multimedia Version 9.0.4.0.9 (Production)
    Oracle Tools Integration Version 9.0.2.0.0 (Production)
    Oracle Tools Common Area Version 9.0.1.0.0
    Oracle CORE     9.0.1.2.0     ProductionI have a module based on stored procedures. I have defined query, lock and update procedure. All of them are working as they should, I mean that when looking at the input and output from these procedures I don't see anything blatantly wrong.
    Now, when I update a table field in the form and call the update stored procedure, this procedure takes the updated values in considerations, updates some more fields, and remove some records.
    It is working as it should, except for two details :
    1- I don't see the values updated by the procedure in the Form;
    2- even though some records were removed from the table by the procedure, I still see all my records.
    Is there a way to display the returned table?
    And, is there any documentation about data block based on stored procedures, what are the required signatures and limitations of those stored procedures, what a lock procedure is supposed to do (mine does 'null;' ...), how to map a collection type defined in Oracle to a Form data block ? Any link will be appreciated, I have found half a dozen page vaguely detailing this on Google, but nothing that can compare to a usual Oracle manual. Maybe I have missed something.
    Thank you for your help.
    adsm

    Yes, I was hoping to use these procedures to map the collection type returned to the database to the block data. I guess I was wrong. Except for the initial query and reading some other information from the database, I don't have to use these procedures as I do not write anything to it.
    Thank you for your help, I will go on from there.
    So, it means that I will have to iterate through my collection inside Forms and manipulate my data row by row. Or, is there a way to pass an Oracle collection type between the database and the Forms client and have it displayed without having to iterate through the rows and mapping each field?
    adsm

  • How do I return two values from a stored procedure into an "Execute SQL Task" within SQL Server 2008 R2

    Hi,
    How do I return two values from a
    stored procedure into an "Execute SQL Task" please? Each of these two values need to be populated into an SSIS variable for later processing, e.g. StartDate and EndDate.
    Thinking about stored procedure output parameters for example. Is there anything special I need to bear in mind to ensure that the SSIS variables are populated with the updated stored procedure output parameter values?
    Something like ?
    CREATE PROCEDURE [etl].[ConvertPeriodToStartAndEndDate]
    @intPeriod INT,
    @strPeriod_Length NVARCHAR(1),
    @dtStart NVARCHAR(8) OUTPUT,
    @dtEnd NVARCHAR(8) OUTPUT
    AS
    then within the SSIS component; -
    Kind Regards,
    Kieran. 
    Kieran Patrick Wood http://www.innovativebusinessintelligence.com http://uk.linkedin.com/in/kieranpatrickwood http://kieranwood.wordpress.com/

    Below execute statement should work along the parameter mapping which you have provided. Also try specifying the parameter size property as default.
    Exec [etl].[ConvertPeriodToStartAndEndDate] ?,?,? output, ? output
    Add a script task to check ssis variables values using,
    Msgbox(Dts.Variables("User::strExtractStartDate").Value)
    Do not forget to add the property "readOnlyVariables" as strExtractStartDate variable to check for only one variable.
    Regards, RSingh

  • Missing parameter in stored procedure

    Hi all,
    I am new to Crystal Report, and I am facing this situation:
    a file .rpt reporting results of a sql server stored procedure, which takes one parameter in input.
    This .rpt is invoked by an .net web service, via libraries, passing the parameter.
    Now I evolved this stored procedure by adding a new parameter. Each of the two parameter is optional; the stored
    procedure returns correctly formatted data with one parameter, the other one, both or none.
    Then I adapted the .rpt file so that it can manage the updated stored procedure, via "Verify Database" istruction.
    Also the .rpt has obviously two input parameters now, with a default value.
    The problem is, the web service acting as handler gives the error "Missing parameter values", because actually it is passing still
    one parameter.
    If I update the web service code by passing both parameters, even with null value, it works, but for internal reasons I can't deploy
    this updated code now
    So, there is a way by modifying the .rpt using a stored procedure with two parameters, to make the invocation successfully even with one input parameter ?
    The missing parameter would have, in the execution logic now, value null or default; it could fit for me.
    Thanks in advance to everyone who will give advice!

    Thanks Don for your answer.
    Unless you change the SP so it has the logic to accept only one value which depends on the parameter type, if they are both strings for example then your SP can use logic the determine what/which param to fill and null the other one.
    What do you mean? Now if I call my stored procedure from SQL Server management studio with this command
    EXEC     [dbo].[StoredProcedureForCR] @FirstParameter = 2
    so, passing only the first parameter, I have no error.
    Which improvements to the SP are you suggesting?
    If I modify the web service, the CR is working, but I cannot deploy it in production for internal reasons related to the company
    Now I am planning these attempts:
    - calling the stored procedure via a command
    - creating in sql server a view and then filtering results in the report
    Do you think they could make sense ?
    Have a nice monday!
    Lidia

  • With clause in a stored procedure with update

    create table TEMP_STAGE as
    (select '111111' student_id, 'N' TMP_TEST FROM DUAL
    UNION
    select '111111' student_id, 'N' TMP_TEST FROM DUAL
    UNION
    select '222222' student_id, 'N' TMP_TEST FROM DUAL
    CREATE OR REPLACE PROCEDURE TEMP_SEC_TEST
    AS
    BEGIN
    UPDATE TEMP_STAGE S
    SET S.TMP_TEST = 'Y'
    WHERE STUDENT_ID IN
    WITH MARK AS
    SELECT '111111' STUDENT_ID FROM DUAL
    select STUDENT_ID from MARK
    END;
    I have a huge sql statement with several 'with' tables in the statement...It works if I execute it as a script but it does not work when I put it in a stored procedure.
    When I execute the above it gives me an error...
    Error Syntax Check (8:9)
    Found 'MARK' expecting .....
    It gives me an error at the wth Mark as line....
    I have to do it in the stored procedure as the statement is very complicated...
    Please help.

    What tool are you using to create the procedure? Error Syntax Check (8:9) is not an Oracle error, nor as far as I know from any Oracle product.
    It works just fine in sqlplus.
    SQL> CREATE procedure my_p AS
      2  BEGIN
      3     UPDATE t
      4     SET descr = 'Un'
      5     WHERE id IN (WITH tmp AS (
      6                     SELECT 1 x FROM dual)
      7                  SELECT x FROM tmp);
      8  END;
      9  /
    Procedure created.
    SQL> SELECT * FROM t;
            ID DESCR
             1 One
    SQL> exec my_p;
    PL/SQL procedure successfully completed.
    SQL> SELECT * FROM t;
            ID DESCR
             1 UnJohn

  • Can we have an example of using update, insert, and delete stored procedure

    I would like to see an example of using retrieve (return resultset), update, insert, and delete stored procedures in JSF. I need to see syntax how JSF can call those stored procedures. This option is absolutely important when building web-application. Currently, I haven't found resource to do for this purpose yet. The database can be any such Oracle, DB2, pointbase, etc that support stored procedures.
    Anyone knows?
    Thanks,
    Tue Vu

    Hi ttv,
    I asked around a bit and here's some more info:
    To bind a ResultSet to a read only Data Table component just set the "value" property of the Data Table component to point at it, and JSF will synthesize a DataModel around it.
    * Note that because we can't call the stored procedure at design time, Creator can't do the fancy table layout stuff it does for rowsets. You'll need to hand craft the columns just like the Google Client example.
    * As I mentioned previously, you will have to manually code the stored procedure access in your java code - see the code clip I mentioned in previous reply (and if this is via a stored procedure, then any textbook about JDBC will undoubtedly have examples). Simplest way might be a getter method on the page bean that contains the call to the stored procedure and returns the resulting ResultSet object.
    * Don't forget to close the result set - we typically do this at the end of the request (i.e. add a close in the afterRenderResponse() method.
    * Don't throw exceptions - or if you have to, make sure you close the result set in a finally clause (thrown exceptions bypass the afterRenderResponse method in the lifecycle).
    * You give up on the caching provided by our RowSetDataModel (which can't be connected to a ResultSet even manually), so I would recommend that you only use datatables to display the data and then go to a single row page to do edits/deletes (similar to the TwoPage example in AppModel and the Update, Insert Delete tutorial).
    And yes please do submit an example - we will gladly post it!!! :) The best way to submit this kind of thing would be through:
    http://developers.sun.com/prodtech/javatools/jscreator/reference/codesamples/sampleapps.html
    on the right side, Related Links, under Creator Heros, click Submit Content and there you can send it in!
    Hope this helps!
    Val

  • How to create a stored procedure that contains all 3 AFTER Triggers Update/Insert/Delete ?

    Hi guys, I'm trying to create a Stored procedure that will automatically add all 3 After triggers when executed on any given database, can someone please explain and give an example on how do I go about doing this ? I'd also like it to raise any errors
    that may come across, thanks in advance.

    Lets start with the question why do you need the triggers at all. Since SQL Server 2005 we can use an OUTPUT clause.
    This code can be re-written in SQL Server 2005 using the OUTPUT clause like below:
    create table itest ( i int identity not null primary key, j int not null unique )
    create table #new ( i int not null, j int not null)
    insert into itest (j)
    output inserted.i, inserted.j into #new
    select o.object_id from sys.objects as o
    select * from #new
    drop table #new, itest;
    go
    Now from this example, you can see the integration of OUTPUT clause with existing DML syntax.
    Another common scenario is auditing of data in a table using triggers. In this case, the trigger uses information from the inserted and updated tables to add rows into the audit tables. The example below shows code that uses OUTPUT clause in UPDATE and DELETE
    statements to insert rows into an audit table.
    create table t ( i int not null );
    create table t_audit ( old_i int not null, new_i int null );
    insert into t (i) values( 1 );
    insert into t (i) values( 2 );
    update t
       set i  = i + 1
    output deleted.i, inserted.i into t_audit
     where i = 1;
    delete from t
    output deleted.i, NULL into t_audit
     where i = 2;
    select * from t;
    select * from t_audit;
    drop table t, t_audit;
    go
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • How to get an updatable ADODB Recordset from a Stored Procedure?

    In VB6 I have this code to get a disconnected ADODB Recordset from a Oracle 9i database (the Oracle Client is 10g):
    Dim conSQL As ADODB.Connection
    Dim comSQL As ADODB.Command
    Dim recSQL As ADODB.Recordset
    Set conSQL = New ADODB.Connection
    With conSQL
    .ConnectionString = "Provider=OraOLEDB.Oracle;Password=<pwd>;Persist Security Info=True;User ID=<uid>;Data Source=<dsn>"
    .CursorLocation = adUseClientBatch
    .Open
    End With
    Set comSQL = New ADODB.Command
    With comSQL
    .ActiveConnection = conSQL
    .CommandType = adCmdStoredProc
    .CommandText = "P_PARAM.GETALLPARAM"
    .Properties("PLSQLRSet").Value = True
    End With
    Set recSQL = New ADODB.Recordset
    With recSQL
    Set .Source = comSQL
    .CursorLocation = adUseClient
    .CursorType = adOpenStatic
    .LockType = adLockBatchOptimistic
    .Open
    .ActiveConnection = Nothing
    End With
    The PL/SQL Procedure is returning a REF CURSOR like this:
    PROCEDURE GetAllParam(op_PARAMRecCur IN OUT P_PARAM.PARAMRecCur)
    IS
    BEGIN
    OPEN op_PARAMRecCur FOR
    SELECT *
    FROM PARAM
    ORDER BY ANNPARAM DESC;
    END GetAllParam;
    When I try to update some values in the ADODB Recordset (still disconnected), I get the following error:
    Err.Description: Multiple-step operation generated errors. Check each status value.
    Err.Number: -2147217887 (80040E21)
    Err.Source: Microsoft Cursor Engine
    The following properties on the Command object doesn't change anything:
    .Properties("IRowsetChange") = True
    .Properties("Updatability") = 7
    How can I get an updatable ADODB Recordset from a Stored Procedure?

    4 years later...
    I was having then same problem.
    Finally, I've found how to "touch" the requierd bits.
    Obviously, it's hardcore, but since some stupid at microsoft cannot understand the use of a disconnected recordset in the real world, there is no other choice.
    Reference: http://download.microsoft.com/downlo...MS-ADTG%5D.pdf
    http://msdn.microsoft.com/en-us/library/cc221950.aspx
    http://www.xtremevbtalk.com/showthread.php?t=165799
    Solution (VB6):
    <pre>
    Dim Rst As Recordset
    Rst.Open "select 1 as C1, '5CHARS' as C5, sysdate as C6, NVL(null,15) as C7, null as C8 from DUAL", yourconnection, adOpenKeyset, adLockBatchOptimistic
    Set Rst.ActiveConnection = Nothing
    Dim S As New ADODB.Stream
    Rst.Save S, adPersistADTG
    Rst.Close
    Set Rst = Nothing
    With S
    'Debug.Print .Size
    Dim Bytes() As Byte
    Dim WordVal As Integer
    Dim LongVal As Long
    Bytes = .Read(2)
    If Bytes(0) <> 1 Then Err.Raise 5, , "ADTG byte 0, se esperaba: 1 (header)"
    .Position = 2 + Bytes(1)
    Bytes = .Read(3)
    If Bytes(0) <> 2 Then Err.Raise 5, , "ADTG byte 9, se esperaba: 2 (handler)"
    LongVal = Bytes(1) + Bytes(2) * 256 ' handler size
    .Position = .Position + LongVal
    Bytes = .Read(3)
    If Bytes(0) <> 3 Then Err.Raise 5, , "ADTG, se esperaba: 3 (result descriptor)"
    LongVal = Bytes(1) + Bytes(2) * 256 ' result descriptor size
    .Position = .Position + LongVal
    Bytes = .Read(3)
    If Bytes(0) <> 16 Then Err.Raise 5, , "ADTG, se esperaba: 16 (adtgRecordSetContext)"
    LongVal = Bytes(1) + Bytes(2) * 256 ' token size
    .Position = .Position + LongVal
    Bytes = .Read(3)
    If Bytes(0) <> 5 Then Err.Raise 5, , "ADTG, se esperaba: 5 (adtgTableDescriptor)"
    LongVal = Bytes(1) + Bytes(2) * 256 ' token size
    .Position = .Position + LongVal
    Bytes = .Read(1)
    If Bytes(0) <> 6 Then Err.Raise 5, , "ADTG, se esperaba: 6 (adtgTokenColumnDescriptor)"
    Do ' For each Field
    Bytes = .Read(2)
    LongVal = Bytes(0) + Bytes(1) * 256 ' token size
    Dim NextTokenPos As Long
    NextTokenPos = .Position + LongVal
    Dim PresenceMap As Long
    Bytes = .Read(3)
    PresenceMap = Val("&H" & Right$("0" & Hex$(Bytes(0)), 2) & Right$("0" & Hex$(Bytes(1)), 2) & Right$("0" & Hex$(Bytes(2)), 2))
    Bytes = .Read(2) 'ColumnOrdinal
    'WordVal = Val("&H" & Right$("0" & Hex$(Bytes(0)), 2) & Right$("0" & Hex$(bytes(1)), 2))
    'Aca pueden venir: friendly_columnname, basetable_ordinal,basetab_column_ordinal,basetab_colname
    If PresenceMap And &H800000 Then 'friendly_columnname
    Bytes = .Read(2) 'Size
    LongVal = Bytes(0) + Bytes(1) * 256 ' Size
    .Position = .Position + LongVal * 2 '*2 debido a UNICODE
    End If
    If PresenceMap And &H400000 Then 'basetable_ordinal
    .Position = .Position + 2 ' 2 bytes
    End If
    If PresenceMap And &H200000 Then 'basetab_column_ordinal
    .Position = .Position + 2 ' 2 bytes
    End If
    If PresenceMap And &H100000 Then 'basetab_colname
    Bytes = .Read(2) 'Size
    LongVal = Bytes(0) + Bytes(1) * 256 ' Size
    .Position = .Position + LongVal * 2 '*2 debido a UNICODE
    End If
    Bytes = .Read(2) 'adtgColumnDBType
    'WordVal = Val("&H" & Right$("0" & Hex$(Bytes(0)), 2) & Right$("0" & Hex$(bytes(1)), 2))
    Bytes = .Read(4) 'adtgColumnMaxLength
    'LongVal = Val("&H" & Right$("0" & Hex$(Bytes(3)), 2) & Right$("0" & Hex$(Bytes(2)), 2) & Right$("0" & Hex$(Bytes(1)), 2) & Right$("0" & Hex$(Bytes(0)), 2))
    Bytes = .Read(4) 'Precision
    'LongVal = Val("&H" & Right$("0" & Hex$(Bytes(3)), 2) & Right$("0" & Hex$(Bytes(2)), 2) & Right$("0" & Hex$(Bytes(1)), 2) & Right$("0" & Hex$(Bytes(0)), 2))
    Bytes = .Read(4) 'Scale
    'LongVal = Val("&H" & Right$("0" & Hex$(Bytes(3)), 2) & Right$("0" & Hex$(Bytes(2)), 2) & Right$("0" & Hex$(Bytes(1)), 2) & Right$("0" & Hex$(Bytes(0)), 2))
    Dim ColumnFlags() As Byte, NewFlag0 As Byte
    ColumnFlags = .Read(1) 'DBCOLUMNFLAGS, First Byte only (DBCOLUMNFLAGS=4 bytes total)
    NewFlag0 = ColumnFlags(0)
    If (NewFlag0 And &H4) = 0 Then 'DBCOLUMNFLAGS_WRITE (bit 2) esta OFF
    'Lo pongo en ON, ya que quiero escribir esta columna LOCALMENTE en el rst DESCONECTADO
    NewFlag0 = (NewFlag0 Or &H4)
    End If
    If (NewFlag0 And &H8) <> 0 Then 'DBCOLUMNFLAGS_WRITEUNKNOWN (bit 3) esta ON
    'Lo pongo en OFF, ya que no me importa si NO sabes si se puede updatear no, yo lo se, no te preocupes
    'ya que quiero escribir esta columna LOCALMENTE en el rst DESCONECTADO
    NewFlag0 = (NewFlag0 And Not &H8)
    End If
    If (NewFlag0 And &H20) <> 0 Then 'DBCOLUMNFLAGS_ISNULLABLE (bit 5) esta OFF
    'Lo pongo en ON, ya que siendo un RST DESCONECTADO, si le quiero poner NULL, le pongo y listo
    NewFlag0 = (NewFlag0 Or &H20)
    End If
    If NewFlag0 <> ColumnFlags(0) Then
    ColumnFlags(0) = NewFlag0
    .Position = .Position - 1
    .Write ColumnFlags
    End If
    .Position = NextTokenPos
    Bytes = .Read(1)
    Loop While Bytes(0) = 6
    'Reconstruyo el Rst desde el stream
    S.Position = 0
    Set Rst = New Recordset
    Rst.Open S
    End With
    'TEST IT
    On Error Resume Next
    Rst!C1 = 15
    Rst!C5 = "MUCHOS CHARS"
    Rst!C7 = 23423
    If Err.Number = 0 Then
    MsgBox "OK"
    Else
    MsgBox Err.Description
    End If
    </pre>

  • Strange error while executing a stored procedure: Incorrect syntax near '@p0'

    All, I am getting a strange error while executing a stored procedure: Incorrect syntax near '@p0'  using JDBC CallableStatment.
    Here is my code...
    CallableStatement cStmt = con.prepareCall("{call SET CHAINED ON EXEC <dbName>.<schemaName>.<SPName> (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
    cStmt.setString(1, "2012005881");
    cStmt.setString(2, "07");
    cStmt.setString(3, "10");
    cStmt.setString(4, "Case title");
    cStmt.setString(5, "Open");
    java.sql.Date dt1 = new java.sql.Date(2014,10,20);
    cStmt.setDate(6, dt1);
    cStmt.setString(7, "01");
    cStmt.setString(8, "N");
    cStmt.setString(9, "ADA Test");
    cStmt.setString(10, "N");
    cStmt.setString(11, "English");
    cStmt.setString(12, "N");
    cStmt.setString(13, "N");
    cStmt.setString(14, "N");
    cStmt.setString(15, "N");
    cStmt.setString(16, "N");
    cStmt.setString(17, "N");
    cStmt.setString(18, "07");
    cStmt.setString(19, "10");
    cStmt.setString(20, "juache0");
    java.sql.Date dt2 = new java.sql.Date(2014,10,20);
    java.sql.Date dt3 = new java.sql.Date(2014,10,20);
    cStmt.setDate(21, dt2);
    cStmt.setDate(22, dt3);
    cStmt.setString(23, "userid0");
    cStmt.setString(24, "");
    cStmt.setString(25, "");  
    cStmt.setString(26, "");
    java.math.BigDecimal bg1 = new java.math.BigDecimal(10);
    cStmt.setBigDecimal(27, bg1);
    cStmt.setString(28, "userid");
    cStmt.setString(29, "userid");
    int hadResults = cStmt.executeUpdate();
    Your help is greatly appreciated.
    I am executing the above using Jconnect3.0 driver, inside WebSphere Application Server V8.0
    Thanks
    Nags

    NOTE: I don't work with JDBC/jConnect so (at this point) just some questions ...
    1 - are you sending this to ASE, ASA, IQ, or some other RDBMS?
    2 - what is the value of <schemaname>?
    3 - do you have other prepareCall() instances that successfully call a stored proc? [would be interesting to see if there's a difference in the format of the calls]
    A quick google search shows a couple ways to submit a stored proc execution to the RDBMS, with the format depending on the format expected by the target RDBMS.
    I'm wondering if you really need/want the parentheses around the argument list, ie, what happens if you change
    from
    -- parentheses around args
    EXEC <dbName>.<schemaName>.<SPName> ( ?,?,?,?,?,...,? )
    to
    -- no parentheses around args
    EXEC <dbName>.<schemaName>.<SPName> ?,?,?,?,?,...,?
    In ASE if I wrap the parameters in parentheses I get the same error you're getting:
    ================== w/ parentheses => error
    1> sp_who (sa)
    2> go
    Msg 102, Level 15, State 1:
    Server 'CC1_V1', Line 1:
    Incorrect syntax near 'sa'.   <<=== sa == @p0 ??
    ================== w/out parentheses => works
    1> sp_who sa
    2> go
    fid spid status  loginame origname ...
       0   17 running sa       sa       ...
    ==================

  • Calling a stored procedure before row update without using triggers

    I have got two tables Main Table(Table1) and History Table(Table2), whenever an update is done on Table1 i want to insert the old row before update to Table2, so that i have history available for that record.
    My doubt is
    how to refer to old value (values b4 update) in a stored procedure?
    how to call a stored procedure b4 every row update(on the database side as we do with tiggers)?
    I want to write a stored procedure where in i will insert the old row values ( value b4 update ) to Table2.
    Any Help would be great....

    sample code calling procedure before insert:
    DriverManager.registerDriver(new someDriver);
    Connection conn = DriverManager.getConnection(driver,uname,pword);
    CallableStatement cs = conn.prepareCall("{call procedureName(?,?)}");
              cs.setString(1,userName);
              cs.registerOutParameter(2,Types.VARCHAR);
              cs.execute();
              success = cs.getString(2);
              PreparedStatement pstmt = conn.prepareStatement("insert into sometable values(?,?)");
              pstmt.setString(1,userName);
              pstmt.setString(2,password);
              pstmt.executeUpdate();     
              conn.commit();      
              cs.close();
           conn.close();

  • Incorrect Update Count by executing a stored procedure from Java

    Hi Guys,
    I am calling a stored procedure from the java program which is modifying the rows of a table. Now I want to know how many rows have been modified by executing the stored procedure. I am writing the following code for the purpose:
    OracleCallableStatement stmt =
    (oracle.jdbc.driver.OracleCallableStatement)con.prepareCall("{callsp_um_setForumID(?,?)}");
    stmt.setInt(1,101);
    stmt.setInt(2,666);
    n = stmt.executeUpdate();
    System.out.println(n + " row(s) updated");
    This procedure is actually modifying the table(When I query the databse it has modified 1 row). But it is returning a value 0 and is printing "0 row(s) updated".
    Is there a way by which I can find out the number of rows updated by executing the stored procedure?
    Thanks
    Sachin
    [email protected]

    I'm no expert on this, but I have a similar call where I fetch
    an Oracle REF CURSOR from a call to a stored function. If you
    fetch the cursor as an Object from your CallableStatement, you
    can then cast it to a ResultSet e.g.
    mystatement.executeUpdate();
    ResultSet rs = (ResultSet) mystatement.getObject(1);
    Then you should be able to loop through your ResultSet as usual.
    Good luck!
    Chris

Maybe you are looking for