Stored Procedure creation issue

Hi All,
I need a stored procedure's for below Scenario:
tblProduct is a parameter table that has values list of Products and every product has code (Eg, PEN A, BOOK B , PENCIL C and so on)
For every value a procedure sp_findIndex will be called 
sp_findIndex finds the index of the alphabet based on the tblKeyValue a key value table which has two columns key and value, key 1,2,3....
and values A,B,C..
Further sp_findIndex calls sp_evenOdd with
the index as input and provides an output whether index is an even or an odd number 
which is printed through sp_findIndex procedure 
Task 1
List down even and odd for all the products.
Task 2
Now warp this logic to stored procedure sp_wrapper which takes input Product names separated by comma.
Thanks in Advance.........
Tbl_Product
Create table Tbl_Product
Product varchar(50) NULL,
Code Varchar (50) NULL
Insert into Tbl_Product values('PEN','A')
Insert into Tbl_Product values('BOOK','B')
Insert into Tbl_Product values('PENCIL','C')
Insert into Tbl_Product values('TV','D')
Insert into Tbl_Product values('COMPUTER','E')
Insert into Tbl_Product values('SHOES','F')
Insert into Tbl_Product values('SHIRT','G')
Tab_KeyValue
Create table tbl_KeyValue
value char(3) NULL,
keys int NULL
Insert into tbl_Keyvalue values('A',1)
Insert into tbl_Keyvalue values('B',2)
Insert into tbl_Keyvalue values('C',3)
Insert into tbl_Keyvalue values('D',4)
Insert into tbl_Keyvalue values('E',5)
Insert into tbl_Keyvalue values('F',6)
Insert into tbl_Keyvalue values('G',7)
Main
Procedure:
CREATE PROCEDURE DBO.SP_WRAPPD
(PRODUCT1 VARCHAR(1000))
AS
BEGIN
DECLARE @COMMA VARCHAR(2)
SET @COMMA =','
SELECT CODE FROM TBL_PRODUCT WHERE CHARINDEX(PRODUCT,@PRODUCT) >0
END
Second
procedure:
Create Procure sp_findIndexes(@value varchar(10))
as
begin
Declare @keys int
set @Keys =(select A.keys from tbl_keyvalue A where A.value=@value)
Declare @Evenodd varchar(10)
Declare @result int
Exec @result =sp_EvenOdds @keys
if @result=1
set @EvenOdd ='Even'
else
set @EvenOdd='Odd'
insert into ##EvenOddResultss select A.keys,B.Product,@evenodd as evenodd from tbl_product B
inner join
tbl_KeyValue A
on A.Value=B.code and A.keys=@keys
end
Third
Procedure:
Create procedure sp_EvenOdds (@Key int)
as
begin
if(@key%2=0)
return(1)
else
return(0)
end
I am calling third procure from second,second from Main Procedure...
Thanks in Advance...

Hi,
1. Again this is a image and not a code!
Do you want to waste our time on typing while we can help other people?!?
Isn't it more helpful to use copy/paste and to bring us a code and not stories/images? 
2. How can we recreate the issue and execute or even just create this SP without having the relevant elements (like the tables) ?!?
Please post DDL+DML!
DDL = Data Definition Language. In our case that is, CREATE TABLE statements for your tables and other definitions that are needed to understand your tables structure and there for let us to test and recreate the problem in our server. Without DDL no one
can execute any query.
How to get DDL: Right click on the table in Object Explorer and select script table as CREATE. Post these create table scripts here.
DML = data manipulation language is a family of queries used for manipulating the data it self like: inserting, deleting and updating data. In our case we need some sample data in order to check the query and get result, so we need some indert query for
sample data.
If you post a "create query" for the tables and "insert query" with some sample, then we could help you without Assuming/Guessing. There is a reason that DDL is generally asked for and expected when discussing query problems - it helps
to identify issues, clarify terminology and prevent incorrect assumptions.  Sample data also provides a common point of reference for the discussion. A script that can be used to illustrate or reproduce the issue you have, will encourage others to help.
[Personal Site] [Blog] [Facebook]
Hi Pituach,
Tbl_Product
Create table Tbl_Product
Product varchar(50) NULL,
Code Varchar (50) NULL
Insert into Tbl_Product values('PEN','A')
Insert into Tbl_Product values('BOOK','B')
Insert into Tbl_Product values('PENCIL','C')
Insert into Tbl_Product values('TV','D')
Insert into Tbl_Product values('COMPUTER','E')
Insert into Tbl_Product values('SHOES','F')
Insert into Tbl_Product values('SHIRT','G')
Tab_KeyValue
Create table tbl_KeyValue
value char(3) NULL,
keys int NULL
Insert into tbl_Keyvalue values('A',1)
Insert into tbl_Keyvalue values('B',2)
Insert into tbl_Keyvalue values('C',3)
Insert into tbl_Keyvalue values('D',4)
Insert into tbl_Keyvalue values('E',5)
Insert into tbl_Keyvalue values('F',6)
Insert into tbl_Keyvalue values('G',7)
Main Procedure:
CREATE PROCEDURE DBO.SP_WRAPPD
(PRODUCT1 VARCHAR(1000))
AS
BEGIN
DECLARE @COMMA VARCHAR(2)
SET @COMMA =','
SELECT CODE FROM TBL_PRODUCT WHERE CHARINDEX(PRODUCT,@PRODUCT) >0
END
Second procedure:
Create Procure sp_findIndexes(@value varchar(10))
as
begin
Declare @keys int
set @Keys =(select A.keys from tbl_keyvalue A where A.value=@value)
Declare @Evenodd varchar(10)
Declare @result int
Exec @result =sp_EvenOdds @keys
if @result=1
set @EvenOdd ='Even'
else
set @EvenOdd='Odd'
insert into ##EvenOddResultss select A.keys,B.Product,@evenodd as evenodd from tbl_product B
inner join
tbl_KeyValue A
on A.Value=B.code and A.keys=@keys
end
Third Procedure:
Create procedure sp_EvenOdds (@Key int)
as
begin
if(@key%2=0)
return(1)
else
return(0)
end
I am calling third procure from second,second from Main Procedure

Similar Messages

  • Stored Procedure Command issues in CS3

    I've been having a problem using some stored procedures in
    CS3 which had previously worked with no issue in 8.0.2. I'm running
    CS3 on a Mac for ASP & SQL Server 2000.
    The input parameters for the stored procedure are...
    Fieldname: CategoryID (int) length: 4
    Fieldname: Men (bit) length: 1
    Fieldname: Women(bit) length:1
    I have no problem using the Command function to call this
    stored procedure in DW 8.0.2, but in CS3, while I am able to TEST
    the recordset successfully within the Command dialog, when I press
    OK and then attempt to view the field list in the Bindings panel, I
    get this error...
    [Microsoft][ODBC SQL Server Driver][SQL Server]Procedure
    'spCategoryProduct' expects parameter '@Men', which was not
    supplied.
    When I open up the command settings dialog again, Default
    Values and the Runtime Values I entered for the Men and Women bit
    parameter are blank. The only Default Value and Runtime Value
    retained is for the field CategoryID.
    CS3 is able to call other stored procedures which do not
    contain a Bit field type without issue, so I'm curious if this is
    the culprit.
    I have DW8.0.2 still installed on the same system, and have
    been able to call this stored procedure in this older version,
    without any problems.
    Please help!

    Holy thread-resurrection Batman!
    Please open a new dicussion after reading the bi4.0 data access guide: http://help.sap.com/businessobject/product_guides/boexir4/en/xi4sp5_data_acs_en.pdf
    Also, please specify which SP and Patch you are using.
    Regards,
    H

  • Stored Procedure/Variable issue

    Hopefully this is the last issue to work through... but we need to access images stored on another server. We have a stored procedure called 'get_doc' that accesses the image file, and we've successfully tested it with a hardcoded value. A button calls a process that executes the following PL/SQL:
    get_doc (
    p=> 77456);
    However, when I use the same process with a variable on the page (which has the same numeric value of 77456), the procedure says the value of p is Null.
    get_doc (
    p=> :P7_STARTERNUM);
    Any suggestions or advice?
    (Using ApEx 4.0 in IE8)

    CPate  wrote:
    Yes, the connection is correct. And I swapped in the hardcode number, the process does what it is supposed to and returns the image. Swap back in the variable (with to_number as well, just to be sure) and it returns null.
    I tried debugging it and didn't see where P7_STARTERNUM was changed. It just says:
    ..Process "STARTERGET": PLSQL (AFTER_SUBMIT) get_doc (p=> to_number(:P7_STARTERNUM));The trace should look something like:
    0.00275     0.00220     A C C E P T: Request="SAVE"
    0.00484     0.00801     Metadata: Fetch application definition and shortcuts
    0.01291     0.00110     alter session set nls_language="ENGLISH"
    0.01399     0.00069     alter session set nls_territory="UNITED KINGDOM"
    0.01476     0.00084     NLS: CSV charset=WE8MSWIN1252
    0.06085     0.00087     Session State: Save form items and p_arg_values
    0.06173     0.00146     ...Session State: Save "P7_CUSTOMER_ID" - saving same value: "7"
    0.06319     0.00264     ...Session State: Save Item "P7_CUST_FIRST_NAME" newValue="Eugene" "escape_on_input="N"     
    0.33200     0.00090     Processing point: After Submit
    0.33285     0.11813     ...Process "Process Row of DEMO_CUSTOMERS": DML_PROCESS_ROW (AFTER_SUBMIT) #OWNER#:DEMO_CUSTOMERS:P7_CUSTOMER_ID:CUSTOMER_ID|IUD
    {code}
    There should be a session state change like those shown recorded for your <tt>P7_STARTERNUM</tt> item.
    What's the *Display As* type of the <tt>P7_STARTERNUM</tt> item?
    the procedure says the value of p is Null.
    How do you know this?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Can someone help me diagnose a strange stored procedure performance issue please?

    I have a stored procedure (posted below) that returns message recommendations based upon the Yammer Networks you have selected. If I choose one network this query takes less than one second. If I choose another this query takes 9 - 12 seconds.
    /****** Object: StoredProcedure [dbo].[MessageView_GetOutOfContextRecommendations_LargeSet] Script Date: 2/18/2015 3:10:35 PM ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE PROCEDURE [dbo].[MessageView_GetOutOfContextRecommendations_LargeSet]
    -- Parameters
    @UserID int,
    @SourceMessageID int = 0
    AS
    BEGIN
    -- variable for @HomeNeworkUserID
    Declare @HomeNeworkUserID int
    -- Set the HomeNetworkID
    Set @HomeNeworkUserID = (Select HomeNetworkUserID From NetworkUser Where UserID = @UserID)
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON
    -- Begin Select Statement
    Select Top 40 [CreatedDate],[FileDownloadUrl],[HasLinkOrAttachment],[ImagePreviewUrl],[LikesCount],[LinkFileName],[LinkType],[MessageID],[MessageSource],[MessageText],[MessageWebUrl],[NetworkID],[NetworkName],[PosterEmailAddress],[PosterFirstName],[PosterImageUrl],[PosterName],[PosterUserName],[PosterWebUrl],[RepliesCount],[Score],[SmallIconUrl],[Subjects],[SubjectsCount],[UserID]
    -- From View
    From [MessageView]
    -- Do Not Return Any Messages That Have Been Recommended To This User Already
    Where [MessageID] Not In (Select MessageID From MessageRecommendationHistory Where UserID = @UserID)
    -- Do Not Return Any Messages Created By This User
    And [UserID] != @UserID
    -- Do Not Return The MessageID
    And [MessageID] != @SourceMessageID
    -- Only return messages for the Networks the user has selected
    And [NetworkID] In (Select NetworkID From NetworkUser Where [HomeNetworkUserID] = @HomeNeworkUserID And [AllowRecommendations] = 1)
    -- Order By [MessageScore] and [MessageCreatedDate] in reverse order
    Order By [Score] desc, [CreatedDate] desc
    ENDThe Actual Execution Plan Shows up the same; there are more messages on the Network that is slow, 2800 versus 1,500 but the difference is ten times longer on the slow network.Is the fact I am doing a Top 40 what makes it slow? My first guess was to take the Order By Off and that didn't seem to make any difference.The execution plan is below, it takes 62% of the query to look up theIX_Message.Score which is the clustered index, so I thought this would be fast. Also the Clustered Index Seek for the User.UserID take 26%which seems high for what it is doing.
    I have indexes on every field that is queried on so I am kind of at a loss as to where to go next.
    It just seems strange because it is the same view being queried in both cases.
    I tried to run the SQL Server Tuning Wizard but it doesn't run on Azure SQL, and my problem doesn't occur on the data in my local database.
    Thanks for any guidance, I know a lot of the slowness is due to the lower tier Azure SQL we are using, many of the performance issues weren't noticed when were on the full SQL Server, but the other networks work extremely fast so it has to be something to
    with having more rows.
    In case you need the SQL for the View that I am querying it is:
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE VIEW [dbo].[MessageView]
    AS
    SELECT M.UserID, M.MessageID, M.NetworkID, N.Name AS NetworkName, M.Subjects, M.SubjectsCount, M.RepliesCount, M.LikesCount, M.CreatedDate, M.MessageText, M.HasLinkOrAttachment, M.Score, M.WebUrl AS MessageWebUrl, U.UserName AS PosterUserName,
    U.Name AS PosterName, U.FirstName AS PosterFirstName, U.ImageUrl AS PosterImageUrl, U.EmailAddress AS PosterEmailAddress, U.WebUrl AS PosterWebUrl, M.MessageSource, M.ImagePreviewUrl, M.LinkFileName, M.FileDownloadUrl, M.LinkType, M.SmallIconUrl
    FROM dbo.Message AS M INNER JOIN
    dbo.Network AS N ON M.NetworkID = N.NetworkID INNER JOIN
    dbo.[User] AS U ON M.UserID = U.UserID
    GO
    The Network Table has an Index on Network ID, but it non clustered but I don't think that is the culprit.
    Corby

    I marked your response as answer because you gave me information I didn't have about the sort. I ended up rewriting the query to be a join instead of the In's and it improved dramatically, about one second on a very minimal Azure SQL database, and before
    it was 12 seconds on one network. We didn't notice the problem at all before we moved to Azure SQL, it was about one - three seconds at most.
    Here is the updated way that was much more efficient:
    CREATE PROCEDURE [dbo].[Procedure Name]
    -- Parameters
    @UserID int,
    @SourceMessageID int = 0
    AS
    BEGIN
    -- variable for @HomeNeworkUserID
    Declare @HomeNeworkUserID int
    -- Set the HomeNetworkID
    Set @HomeNeworkUserID = (Select HomeNetworkUserID From NetworkUser Where UserID = @UserID)
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON
    ;With cteMessages As
    -- Begin Select Statement
    Select (Fields List)
    -- Join to Network Table
    From MessageView mv Inner Join NetworkUser nu on MV.NetworkID = nu.NetworKID -- Only Return Networks This User Has Selected
    Where nu.HomeNetworkUserID = @HomeNeworkUserID And AllowRecommendations = 1
    -- Do Not Return Any Messages Created By This User
    And mv.[UserID] != @UserID
    -- Do Not Return The MessageID
    And mv.[MessageID] != @SourceMessageID
    ), cteHistoryForThisUser As
    Select MessageID From MessageRecommendationHistory Where UserID = @UserID
    -- Begin Select Statement
    Select Top 40 (Fields List)
    -- Join to Network Table
    From cteMessages m Left Outer Join cteHistoryForThisUser h on m.MessageID = h.MessageID
    -- Do Not Return Any Items Where User Has Already been shown this Message
    Where h.MessageID Is Null
    -- An Order By Is Needed To Get The Best Content First
    Order By Score Desc
    END
    GO
    The Left Outer Join to test for null was the biggest improvement, but it also helped to join to the NetworkUser table instead of do the In sub query.

  • Stored procedure Performance issue in SQLserver 2005

    Hi All,
    i am inserting the data to Database by using of Stored procedure in target DB.
    My source structure and target structures are looking below
    I have the source structure having lot of rows and look like my structure is below:
    <?xml version="1.0" encoding="utf-8" ?>
    <ns0:POCA0013_KANLOG_REQUEST_MT_response xmlns:ns0="urn:com:POCA0013:sample">
    <SCMDB_response>
    -  <row>
          <PROJK>O-USA</PROJK>
          <KOLLO>123</KOLLO>
       </row>
    -  <row>
          <PROJK>O-Denmark</PROJK>
          <KOLLO>256</KOLLO>
       </row>
        n  number of rows
    </SCMDB_KANLOGVIEW_response>
    </ns0:POCA0013_KANLOG_REQUEST_MT_response>
    and after mapping my target structure is coming to like this.
    <?xml version="1.0" encoding="UTF-8" ?>
    <ns0:POCA0013_DB_MT xmlns:ns0="urn:pg-com POCA0013:sample">
    <StatmentName>
       <XI_SP_DATA action="EXECUTE">
         <PROJEK isInput="TRUE" type="CHAR">O-USA</PROJEK>
         <KOLLO isInput="TRUE" type="CHAR" >123</KOLLO>
       </XI_SP_DATA>
    </StatmentName>
    <StatmentName>
       <XI_SP_DATA action="EXECUTE">
         <PROJEK isInput="TRUE" type="CHAR">O-Denmark</PROJEK>
         <KOLLO isInput="TRUE" type="CHAR" />256</KOLLO>
       </XI_SP_DATA>
    </StatmentName>
      N number of times
    </ns0:POCA0013_DB_MT>
    this is working perfectly to insert the records into the database by using stored procedure. each record  it call the stored procedure for insert the records, for example we had 100 records and it call 100 times stored procedure.
    But in case of huge data, for example 10000 records, it call the 10000 times to stored procedure.in that case we had a problem for database side.
    we have  one reason to use the stored procedure here, because once insert the data into table, if successful log table is created with successful status , if not log table is created with error status. for that purpose i am using stored procedure here.
    Our customer wants to call the stored procedure for one time for all records.How i can manage this situation.
    Can you give me your valuble ideas about this problem.
    Thank you very much.,
    Sateesh
    Edited by: sateesh kumar .N on Apr 23, 2010 6:53 AM
    Edited by: sateesh kumar .N on Apr 23, 2010 6:54 AM
    Edited by: sateesh kumar .N on Apr 23, 2010 7:54 AM

    Hi Sateesh,
    how about a different approach.
    Add 2 more tables to your solution. The first table is used as a staging table, where PI inserts all the data without making any checks, whatsoever. The second table is used as a control table. If the insertion is finished, a log entry is inserted into this second table, containing the information about success or failure or how many rows had been inserted. Put an insert trigger on this table, which in term starts a stored procedure. This stored procedure can read all the data from the staging table and put it into the desired target tables. Additionally you can perform plausiblitiy checks inside this SP.
    Okay I know, this is a complete new solution in comparison to what you did before. But in my experience, this will be much more performant than 10000 calls to one stored procedure who only does inserts as you described.
    Regards
    Sven

  • Stored Procedure Output Issue in Query Template

    Hi,
    We have written a stored procedure which returns 3 outputs which are of type CLOB. Whenever we call the procedure from query template it gives an error Wrong number or type of parameters. It seems that we need to pass some variables which are of type clob to the procedure while calling which we cannot do as per my knowledge in query template.
    Even if we are able to get the output we will not be getting complete output since the out put values are of type CLOB.
    Can you guide me how to achive this
    Thanks,
    Shalaka

    Hi,
    Sometime back i faced the similar problem. But I used oracle pipelined functions to achieve this....
    The basic thing is it will break the chunk into records of length of 4000 chars and it will return in a table. And from other end you can loop and concatenate. Hope this helps....
    create or replace FUNCTION FN_GEN_XML RETURN dashb_xml pipelined IS v_xml CLOB := NULL;
    v_temp VARCHAR2(4000) := NULL;
    v_counter NUMBER := 1;
    BEGIN
      SELECT somefunction(0)
      INTO v_xml
      FROM dual;--v_xml here is clob type. here you might need to call your proc and get it into this variable.
      dbms_output.put_line ('length of v_xml is:' || length(v_xml));
      DBMS_OUTPUT.PUT_LINE('start of this function');
      LOOP
        v_temp := SUBSTR(v_xml,   v_counter,   4000);
        EXIT
      WHEN v_temp IS NULL;
      DBMS_OUTPUT.PUT_LINE(to_char(v_temp));
      pipe ROW(v_temp);
      v_counter := v_counter + 4000;
    END LOOP;
    RETURN;
    END;
    Regards,
    Ravi Kumar

  • Stored Procedure Performance Issue in Sharepoint Report

    We have a report stored procedure that runs in about 1 minute in production; however, when executed from the Sharepoint it populates, it runs for over 20 minutes, with exactly the same parameters. We've done everything to avoid parameter sniffing problems:
    used WITH RECOMPILE on the procedure declaration; added OPTION OPTIMIZE FOR UNKNOWN on the parameters within queries; even created local variables and assigned the parameter values to them and used them throughout the procedure. None of these has had any effect.
    I know that the 1-base minute run time is a big red flag, and we're working on pre-aggregating this data into our BI platform, but that's months down the liine and this is needed for month-end close every month.
    Other relevant information:
    Sharepoint 2013 on SQL Server 2012
    Data Source is a SQL Server 2008 R2 database
    Report definition created in Visual Studio 2008

    I'm trying to figure out why it's taking so long.  When I query on ExecutionLog3 I see the following (converted to seconds):
    Total Seconds
    Retrieval Seconds
    Processing Seconds
    Rendering Seconds
    ByteCount
    RowCount
    653.966
    653.933
    0.018
    0.015
    15037
    1
    Yet running in SSMS, it completes (consistently) in 62 seconds.

  • Stored Procedure Universe Issues

    Working in version 3.1 SP1 Fix pack 1.8 and created some simple stored procedures to use in the universe and everything worked fine but then due to changing requirements added additional logic to the stored procedures (SQL 2005 database) for the report to include additional prompts and mulitple selects within the code.  With these changes, have encountered multiple errors when trying to insert them in the universe or when we are able to insert them in to the universe then no data ever returns from the new stored procedures even though correct execute statements are being created on the SQL Server and they work on SQL Server and in other BI tools.  Has anyone else encountered this or know of any limitations using stored procedures in universes?

    Holy thread-resurrection Batman!
    Please open a new dicussion after reading the bi4.0 data access guide: http://help.sap.com/businessobject/product_guides/boexir4/en/xi4sp5_data_acs_en.pdf
    Also, please specify which SP and Patch you are using.
    Regards,
    H

  • Bulk Insert Through Stored Procedure performance issue

    Hello,
    i am new to oracle. i am writing a stored procedure through which i want to insert 1 billion record in a table. but it takes days to insert it . please tell me how can i improve performance of my stored procedure. because same stored procedure when i convert it into sql server in take 24 - 30 min to insert 1 billion record.
    Code of my stored procedure are as follows :
    create or replace PROCEDURE bspGenerateHSCode(
    mLoc_id IN INT,
    HSCodeStart IN VARCHAR2,
    HSCodeEnd IN VARCHAR2,
    mRqstId IN INT,
    total_count IN INT,
    Status OUT INT)
    AS
    ExitFlag INT;
    row_count INT;
    mBatchStart NUMBER;
    mBatchEnd NUMBER;
    mStartSqnc NUMBER;
    mEndSqnc NUMBER;
    mHSCode VARCHAR2(500);
    HSStartStr VARCHAR2(500);
    BEGIN
    SELECT COUNT(*) INTO row_count FROM goap_eal_allocation
                   WHERE hs_code_start = HSCodeStart
    AND hs_code_end = HSCodeEnd
    AND loc_id = mLoc_id
    AND processed = 0;
    IF row_count > 0 THEN
    SELECT CAST ( REVERSE(substr(REVERSE(HSCodeStart), 1, instr(REVERSE(HSCodeStart), ',') -1)) AS NUMBER) INTO mStartSqnc FROM DUAL;
    SELECT CAST ( REVERSE(substr(REVERSE(HSCodeEnd), 1, instr(REVERSE(HSCodeEnd), ',') -1)) AS NUMBER) INTO mEndSqnc FROM DUAL;
    SELECT CAST( REVERSE(substr( REVERSE(HSCodeStart), instr(REVERSE(HSCodeStart), ','))) AS VARCHAR2(500) ) INTO HSStartStr FROM DUAL;
    mBatchStart := mStartSqnc;
    DBMS_OUTPUT.PUT_LINE('start batch ' || mBatchStart);
    LOOP
    mBatchEnd := mBatchStart + 5000;
    IF mBatchEnd > mEndSqnc THEN
    mBatchEnd := mEndSqnc + 1;
    END IF;
    DBMS_OUTPUT.PUT_LINE('End batch ' || mBatchEnd);
    LOOP
    mHSCode := HSStartStr || mBatchStart;
    mBatchStart := mBatchStart + 1;
    INSERT INTO goap_eal_register(id, hs_code, loc_id, status_id, synced)
    SELECT CASE WHEN MAX(id) > 0 THEN (MAX(id) + 1) ELSE 1 END AS id ,
    mHSCode, mLoc_id, 6, 1 FROM goap_eal_register;
    EXIT WHEN mBatchStart = mBatchEnd;
    END LOOP;
    COMMIT;
    EXIT WHEN mBatchStart = mEndSqnc +1;
    END LOOP;
    UPDATE goap_eal_allocation SET processed = 1
    WHERE hs_code_start = HSCodeStart
    AND hs_code_end = HSCodeEnd
    AND loc_id = mLoc_id;
    COMMIT;
    Status := 1;
    ELSE
    Status := 0;
    END IF;
    END;
    Thanks

    Please edit your post and add \ on the line before and the line after the code to preserve formattingsee how this looks?
    Also, when you basically just want to RETURN without doing any work then your first test should just RETURN if you don't want to do any work.
    Instead of what your code does:IF row_count > 0 THEN
    . . . a whole lot of code that is hard to read or understand
    COMMIT;
    Status := 1;
    ELSE
    Status := 0;
    END IF;
    Test the condition to determine when you do NOT want proceed and just return.IF row_count = 0 THEN
    Status := 0;
    RETURN;
    END IF;
    -- now NONE of the following code needs to be indented - you won't get here unless you really want to execute it.
    . . . break the code into separate steps and add a one line comment before each step that says what that step does.
    COMMIT;
    Status := 1;

  • How can i create stored procedures dynamically?

    I have tried to create a stored procedure building a string with the PL/SQL code needed to create the procedure. If i run the code using SQL+ works fine, but using the following code:
    Public Sub CreateStoredProcedure()
    Dim strSql As String
    strSql = "CREATE OR REPLACE PACKAGE OPSPRUEBAS AS " & vbCrLf
    strSql = strSql & vbTab & "PROCEDURE consulta (resultado OUT VARCHAR2); " & vbCrLf
    strSql = strSql & "END OPSPRUEBAS; " & vbCrLf
    strSql = strSql & "/ " & vbCrLf
    strSql = strSql & ". " & vbCrLf
    strSql = strSql & "CREATE OR REPLACE PACKAGE BODY OPSPRUEBAS AS " & vbCrLf
    strSql = strSql & "PROCEDURE consulta (resultado OUT VARCHAR2) IS " & vbCrLf
    strSql = strSql & "oc_ref" & vbTab & vbTab & "REF Content_Ontology; " & vbCrLf
    strSql = strSql & "oc" & vbTab & vbTab & "Content_Ontology; " & vbCrLf
    strSql = strSql & "ori" & vbTab & vbTab & "role_def; " & vbCrLf
    strSql = strSql & "ori_ref" & vbTab & vbTab & "ref role_def; " & vbCrLf
    strSql = strSql & "conce" & vbTab & vbTab & "concept; " & vbCrLf
    strSql = strSql & "conce_ref" & vbTab & "REF concept; " & vbCrLf
    strSql = strSql & "b" & vbTab & vbTab & "boolean; " & vbCrLf
    strSql = strSql & "BEGIN " & vbCrLf
    strSql = strSql & "b:=false; " & vbCrLf
    strSql = strSql & "select REF(oi) into ori_ref from rol_table oi where oi.name='Playing'; " & vbCrLf
    strSql = strSql & "select deref(ori_ref) into ori from dual; " & vbCrLf
    strSql = strSql & "select REF(oi) into oc_ref from c_ontologies oi where oi.web_source_prop=websource('FilmContentOntology'); " & vbCrLf
    strSql = strSql & "select deref(oc_ref) into oc from dual; " & vbCrLf
    strSql = strSql & "if oc.if_has_co_class('Film')='TRUE' AND " & vbCrLf
    strSql = strSql & "oc.if_has_co_class('theater')='TRUE' AND " & vbCrLf
    strSql = strSql & "oc.if_has_co_relationship('is_scheduled')='TRUE' AND " & vbCrLf
    strSql = strSql & "oc.if_has_co_attributes('Film', lista('is_scheduled', 'title', 'actor'))='TRUE' AND " & vbCrLf
    strSql = strSql & "oc.if_has_co_attributes('theater', lista('theatername', 'address', 'email'))='TRUE' " & vbCrLf
    strSql = strSql & "then resultado:='FilmContentOntology'; " & vbCrLf
    strSql = strSql & "else resultado:='No Existe'; " & vbCrLf
    strSql = strSql & "end if; " & vbCrLf
    strSql = strSql & "END consulta; " & vbCrLf
    strSql = strSql & "END OPSPRUEBAS; " & vbCrLf
    strSql = strSql & "/ " & vbCrLf
    strSql = strSql & ". " & vbCrLf
    strSql = strSql & "COMMIT;" & vbCrLf
    TextBox2.Text = strSql
    'Dim myConnectionString As String = "User Id=system;Password=daniel;Data Source=websogo;"
    'Dim oraConn As Oracle.DataAccess.Client.OracleConnection = New Oracle.DataAccess.Client.OracleConnection(myConnectionString)
    Dim myCmd As New System.Data.OleDb.OleDbCommand()
    Dim MyConnection As New System.Data.OleDb.OleDbConnection()
    MyConnection.ConnectionString = "Provider=MSDAORA;Data Source=websogo;password=daniel;User ID=system"
    MyConnection.Open()
    'oraConn.Open()
    myCmd.Connection = MyConnection
    myCmd.CommandType = CommandType.Text
    myCmd.CommandText = strSql
    myCmd.ExecuteNonQuery()
    'Dim e As Oracle.DataAccess.Client.OracleException
    'Try
    ' myCmd.ExecuteNonQuery()
    'Catch e
    ' Dim error1 As Oracle.DataAccess.Client.OracleError
    ' error1 = e.Errors.Item(0)
    ' Textbox3.Text = error1.Source & " " & error1.Message
    'End Try
    MyConnection.Close()
    End Sub
    I've tried using Microsoft ODP, OLEDB and Oracle's ODP.NET
    Also tried to catch any error but there are no errors!
    Has anybody achived a successful dynamically stored procedure creation using .net?
    thanks in advance
    Dan

    I'm trying to create Stored Procedures via .NET and able to do so but when I look in Oracle Enterprise Manager Console, the Stored Procedures are marked as INVALID... If I edit the Stored Procedure (i.e. delete a space or something minor) and SAVE then it compiles fine.....
    Any ideas ????
    will be using this against 9i & 10g db

  • Stored Procedure row limit in MII

    Hi,
    We've a transaction that reads data from an Excel sheet and inserts those records in DB by calling a procedure. The application works fine if the rows in Excel is limited to 49. However, if the no. of rows exceed 49, then it doesn't work. On calling the procedure in MII with more than 49 rows of data, MII only returns the first 49 rows.
    We have set the row count in MII to 10000.
    Any inputs?
    Regards
    Rajeev

    Artificially increasing RowCount isn't the answer, especially if aspects in the code need to preallocate memory for resultsets, etc.  In a sense this is why all queries contain the RowCount parameter - to not have unbounded requests (if I'm not mistaken there is also a safety cap override in the code).  Once you've issued an infinite/unbound query to a database, closing the browser will not stop this from continuing to process.
    If you are using something like an SQL stored procedure, then issuing SET ROWCOUNT 0 at the beginning of the procedure will allow sub selects and joins to not fall subject to the RowCount of the query, which like was mentioned, is there more appropriately for the returned resultset.  Of course - this should be used with discretion.

  • Data committed by Stored Procedure can rollback ?

    Hi all !
    I have an application which uses SLSB marked as tx-Required CMT.
    However some business logic is inside Oracle Stored Procedures which issue Commit / Rollback at the end of their job.
    I wonder what happens if, in the end, the EJB rolls back the Container tx ? the data committed by the stored procedure will Rollback ?
    Thanks
    Francesco

    Francesco Marchioni wrote:
    Hi all !
    I have an application which uses SLSB marked as tx-Required CMT.
    However some business logic is inside Oracle Stored Procedures which issue Commit / Rollback at the end of their job.
    I wonder what happens if, in the end, the EJB rolls back the Container tx ? the data committed by the stored procedure will Rollback ?
    Thanks
    FrancescoHi, no. It is an unmanageable situation if WebLogic thinks it's running a
    transaction but some of the procedures being called contain transaction
    control calls. If a procedure calls a commit or rollback, everything in
    the current transaction is affected, and nothing in the future.
    For sanity's sake you must remove all transaction calls from procedures
    if they are to be called from WebLogic transactions.
    Joe

  • Issue while invoking a stored procedure in DB2 from Oracle OSB flow

    oracle.tip.adapter.sa.api.JCABindingException: oracle.tip.adapter.sa.impl.fw.ext.org.collaxa.thirdparty.apache.wsif.WSIFException: servicebus:/WSDL/Test_Project/Application/Project1/TestSP [ TestSP_ptt::TestSP(InputParameters,OutputParameters) ] - WSIF JCA Execute of operation 'TestSP' failed due to: Stored procedure invocation error.
    Error while trying to prepare and execute the NED.LOGIN_MODULE API.
    An error occurred while preparing and executing the NED.LOGIN_MODULE API. Cause: java.lang.NullPointerException
    ; nested exception is:
    BINDING.JCA-11811
    Stored procedure invocation error.
    Error while trying to prepare and execute the NED.LOGIN_MODULE API.
    An error occurred while preparing and executing the NED.LOGIN_MODULE API. Cause: java.lang.NullPointerException
    Check to ensure that the API is defined in the database and that the parameters match the signature of the API.

    This forum is for issues about WebLogic Connector container itself. You may need to post your issue to other forums such as SOA.
    Thanks

  • Issue with sending mail through java stored procedure in Oracle

    Hello
    I am using Oracle 9i DB. I created a java stored procedure to send mail using the code given below. The java class works fine standalone. When its run from Java, mail is sent as desired. But when the java stored procedure is called from pl/sql "Must issue a STARTTLS command first" error is thrown. Please let me know if am missing something. Tried the same code in 11.2.0.2 DB and got the same error
    Error:
    javax.mail.MessagingException: 530 5.7.0 Must issue a STARTTLS command first. va6sm31201010igc.6
    Code for creating java stored procedure: (T1 is the table created for debugging)
    ==================================================
    create or replace and compile java source named "MailUtil1" AS
    import java.util.Enumeration;
    import java.util.Properties;
    import javax.mail.Message;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeMessage;
    public class MailUtil1 {
    public static void sendMailwithSTARTTLS(String host, //smtp.projectp.com
    String from, //sender mail id
    String fromPwd,//sender mail pwd
    String port,//587
    String to,//recepient email ids
    String cc,
    String subject,
    String messageBody) {
    try{
    Properties props = System.getProperties();
    props.put("mail.smtp.starttls.enable", "True"); // added this line
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.user", from);
    props.put("mail.smtp.password", fromPwd);
    props.put("mail.smtp.port", port);
    props.put("mail.smtp.auth", "true");
    #sql { insert into t1 (c1) values ('1'||:host)};
    Session session = Session.getDefaultInstance(props, null);
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));
    #sql { insert into t1 (c1) values ('2')};
    InternetAddress[] toAddress = new InternetAddress[1];
    // To get the array of addresses
    for( int i=0; i < toAddress.length; i++ ) { // changed from a while loop
    toAddress[i] = new InternetAddress(to);
    //System.out.println(Message.RecipientType.TO);
    for( int i=0; i < toAddress.length; i++) { // changed from a while loop
    message.addRecipient(Message.RecipientType.TO, toAddress);
    if (cc!=null) {
    InternetAddress [] ccAddress = new InternetAddress[1];
    for(int j=0;j<ccAddress.length;j++){
    ccAddress[j] = new InternetAddress(cc);
    for (int j=0;j<ccAddress.length;j++){
    message.addRecipient(Message.RecipientType.CC, ccAddress[j]);
    message.setSubject(subject);
    message.setText(messageBody);
    message.saveChanges();
    #sql { insert into t1 (c1) values ('3')};
    Enumeration en = message.getAllHeaderLines();
    String token;
    while(en.hasMoreElements()){
    token ="E:"+en.nextElement().toString();
    #sql { insert into t1 (c1) values (:token)};
    token ="ConTyp:"+message.getContentType();
    #sql { insert into t1 (c1) values (:token)};
    token = "Encod:"+message.getEncoding();
    #sql { insert into t1 (c1) values (:token)};
    token = "Con:"+message.getContent();
    #sql { insert into t1 (c1) values (:token)};
    Transport transport = session.getTransport("smtp");
    #sql { insert into t1 (c1) values ('3.1')};
    transport.connect(host, from, fromPwd);
    #sql { insert into t1 (c1) values ('3.2')};
    transport.sendMessage(message, message.getAllRecipients());
    #sql { insert into t1 (c1) values ('3.3')};
    transport.close();
    #sql { insert into t1 (c1) values ('4')};
    catch(Exception e){
    e.printStackTrace();
    String ex= e.toString();
    try{
    #sql { insert into t1 (c1) values (:ex)};
    catch(Exception e1)
    Edited by: user12050615 on Jan 16, 2012 12:18 AM

    Hello,
    Thanks for the reply. Actually I have seen that post before creating this thread. I thought that I could make use of java mail to work around this problem. I created a java class that succesfully sends mail to SSL host. I tried to call this java class from pl-sql through java stored procedure. That did not work
    So, is this not supported in Oracle ? Please note that I have tested this in both 9i and 11g , in both the versions I got the error. You can refer to the code in the above post.
    Thanks
    Srikanth
    Edited by: user12050615 on Jan 16, 2012 12:17 AM

  • Stored Procedure issue in receiver JDBC synchronous scenario

    Dear Experts,
    Below is the description of the Stored Procedure for my requirement which has 1 input and 7 output.
    CREATE OR REPLACE PROCEDURE emp_det_proc
        p_emp_id IN NUMBER,
        cur_det OUT sys_refCURSOR
    aS
    BEGIN
        OPEN cur_det FOR
        SELECT * FROM EMP_PERSON_VIEW
            WHERE id = p_emp_id;
    END emp_det_proc;
    Inside the procedure , we can see that Select query is done on a VIEW which has some 7 column and these are the output. The data type description of the ID is VARCHAR2 in Oracle Database 11g VIEW, that's why I maintained VARCHAR in Constant mapping at SAP-PI side.
    I am maintaining all the column name present in the view for my JDBC request structure with isOutput and type.
    Below is my JDBC request.
    <?xml version="1.0" encoding="UTF-8" ?>
    - <ns0:MT_ECCJDBC_EmpStrdProc_JDBCReq xmlns:ns0="urn:empdet:sap:jdbc:storedprocedure"> 
    - <Statement> 
    - <emp_det_proc action="EXECUTE"> 
    <table>emp_det_proc</table> 
    <ID isInput="true" type="VARCHAR">200178</ID> 
    </emp_det_proc>
    </Statement>
    </ns0:MT_ECCJDBC_EMPStrdProc_JDBCReq>
    I tested with other XSD type like INT/CHAR/ but with the same error.
    Unable to execute statement for table or stored procedure. 'emp_det_proc' (Structure 'Statement') due to java.sql.SQLException: ORA-06550: line 1, column 7:
    PLS-00306: wrong number or types of arguments in call to 'EMP_DET_PROC'
    ORA-06550: line 1, column 7:
    PL/SQL: Statement ignored
    1. I observed that the Key field ID is maintained as NUMBER in Stored Procedure but in the VIEW it is maintained as VARCHAR2.
    Could anyone help me to solve the issue  with any suggestions?
    Regards
    Rebecca

    Dear Ramesh,
    There are change in the datatype of the Stored Procedure Input parameter. Below is the correct procedure description now.
    Select query of the View
    My JDBC structure
    Observation and querry:
    1. In the SP declaration, there is 1 IN parameter which I have  created in JDBC structure as p_moi_id and gave the type as INTEGER.
    Error : JDBC message processing failed; reason Error processing request in sax parser: Error when executing statement for table/stored proc. 'moi_det_proc' (structure 'Statement'): java.lang.NumberFormatException: For input string: "2*********&49"
    I assume since the range of the number is limited . Integers are values up to 2147483647 and the number I am using is greater than this values.
    2. I assume I have not included the parameter cur_det as OUT. Instead I have maintained the COLUMN names of Select query of the view. Should I remove all the Out parameters which represents inside the View.
    3. What could be the Data type equivalent to Oracle sys_refCURSOR in SAP PI?
    Please share you suggestion.
    Regards
    Rebecca

Maybe you are looking for