Varbinary(max) parameters in Nested Stored Procedures by value or reference _Expand / Collapse

Consider a situation where a stored procedure taking a varbinary(max) (BLOB) input parameter
then calls a nested stored procedure and passes along that varbinary(max) as an input parameter to the nested stored procedure.
Is a copy of the BLOB provided to the nested stored procedure (passed by value) OR is the BLOB passed by reference.
My interest is in understanding the potential memory hit when handling large BLOBs in this environment.
For example, if the BLOB is 200MB, will SQL server need to allocate memory for a new copy each time it's passed to another stored procedure at the next nestlevel?
Looks like table type parameters are passed by reference, but I haven't been able to find any info on BLOBS in this context.

The semantics for parameters in SQL Server is copy-in/copy-out. However, this does not mean that there cannot be optimizations. That is, there is no need to copy the BLOB, as long as the procedure does not change it. Whether they actually have such an optimization,
I don't know.
I composed the repro below, and it is sort of interesting. If I restart my instance (SQL 2014), the memory usage grows with about 40 M for each nesting call, which certainly indicates that the BLOB is copied over and over again. But if I then run it again,
the growth is not the same. This may be because, it uses buffers already available. (A BLOB has to be a handle like a table when it is over some size.) Then again, it means that it is squeezing something else out of the cache.
CREATE PROCEDURE K  @h varchar(MAX) AS
   SELECT SUM(pages_kb)*8192 AS K, datalength(@h) as Dlen FROM sys.dm_os_memory_clerks
   SELECT @h = ''
go
CREATE PROCEDURE L  @h varchar(MAX) AS
   SELECT SUM(pages_kb)*8192 AS L1, datalength(@h) as Dlen FROM sys.dm_os_memory_clerks
   EXEC K @h
   SELECT SUM(pages_kb)*8192 AS L2, datalength(@h) as Dlen FROM sys.dm_os_memory_clerks
   --SELECT @h = ''
go
CREATE PROCEDURE M  @h varchar(MAX) AS
   SELECT SUM(pages_kb)*8192 AS M1, datalength(@h) as Dlen FROM sys.dm_os_memory_clerks
   EXEC L @h
   SELECT SUM(pages_kb)*8192 AS M2, datalength(@h) as Dlen FROM sys.dm_os_memory_clerks
   --SELECT @h = ''
go
CREATE PROCEDURE N  @h varchar(MAX) AS
   SELECT SUM(pages_kb)*8192 AS N1, datalength(@h) as Dlen FROM sys.dm_os_memory_clerks
   EXEC M @h
   SELECT SUM(pages_kb)*8192 AS N2, datalength(@h) as Dlen FROM sys.dm_os_memory_clerks
   --SELECT @h = ''
go
DECLARE @h varchar(MAX) = replicate(cast('ABCD' AS varchar(MAX)), 1E7)
EXEC N @h
go
DROP PROCEDURE K, L, M, N
Erland Sommarskog, SQL Server MVP, [email protected]

Similar Messages

  • StoredProcedureCall with IN OUT Parameters order in Stored Procedure

    Refer to the Toplink documentID:Note 224269.1 - Using IN, OUT and INOUT parameters with StoreProcedureCall. This document can be download from OracleMetaLink:
    http://www.oracle.com/support/metalink/index.html
    I followed the sample code in this document to write a test case for one of complicated PL/SQL codes. The test case showed wrong results for IN/OUT and OUT parameters.
    At the end of the document above, I found this paragraph
    " Check the ordering of the arguments to make sure that they are in the following sequence:
    All 'IN' parameters, All 'OUT' parameters and then all 'INOUT' parameters.
    Your stored procedure must be set up the same way, since this is how values will be passed to it. This is the way in which TopLink stored procedure calls have been designed and implemented. "
    The order of our PL/SQL codes is IN, IN/OUT and OUT. We are not allowed to change our PL/SQL codes because they are currently used in production environment. We do not want to create another versions of PL/SQL codes to comply with IN, OUT, IN/OUT parameter order mentioned above.
    Do you have any work around solution?
    Dennis Nguyen
    LA County Sheriff IT

    I tried a simple example using named parameters and it worked in 9.0.4:
    CREATE OR REPLACE PROCEDURE
    "TEST_904"."STOREDPROCEDURE_INOUT_OUT_IN" (
         P_INOUT IN OUT NUMBER,
         P_OUT OUT NUMBER,
         P_IN NUMBER) AS
    BEGIN
    P_OUT := P_INOUT;
    P_INOUT := P_IN;
    END;
    public void storedProcedureOutInoutInTest() {
         System.out.println("storedProcedureOutInoutInTest");
        StoredProcedureCall call = new StoredProcedureCall();
        call.setProcedureName("STOREDPROCEDURE_INOUT_OUT_IN");
        call.addNamedArgument("P_IN");
        call.addNamedOutputArgument("P_OUT", "P_OUT", Integer.class);
        call.addNamedInOutputArgument("P_INOUT", "P_INOUT", "P_INOUT", Integer.class);
        call.setUsesBinding(true);
        DataReadQuery query = new DataReadQuery();
        query.setCall(call);
        query.addArgument("P_IN");
        query.addArgument("P_INOUT");
        Vector args = new Vector(2);
        args.add(new Integer(1));
        args.add(new Integer(2));
        Object result =  session.executeQuery(query, args);
        Map map = (Map)((Vector)result).firstElement();
        Integer result_p_inout = (Integer)map.get("P_INOUT");
        Integer result_p_out = (Integer)map.get("P_OUT");
         System.out.println("P_INOUT = " +  result_p_inout);
         System.out.println("P_OUT = " +  result_p_out);
    }Result:
    P_INOUT = 1
    P_OUT = 2

  • Get OUTPUT and RETURN parameters from a stored procedure

    I have a stored procedure (MS SQL Server 2008 R2) like the following example.
    Using Database Connectivity I can get the OUTPUT parameters but I can't get de RECORDSET DATA and de RETURN value.
    Does anybody knows how to do that?
    CREATE PROCEDURE [dbo].[TS_Teste] (@T057_S_NOMEMAQUINA VARCHAR(20), @STATUS INT OUTPUT, @ERRO NVARCHAR(500) OUTPUT)
    AS
    BEGIN     
      DECLARE @TABLE TABLE(CODIGO INT, DESCRICAO VARCHAR(30))
      INSERT INTO @TABLE VALUES (51, 'A')     
      INSERT INTO @TABLE VALUES (52, 'B')
      INSERT INTO @TABLE VALUES (53, 'C')
      SELECT * FROM @TABLE
      SET @STATUS = 1
      SET @ERRO = 'Nenhum erro!'
      RETURN 0
    END
    Solved!
    Go to Solution.
    Attachments:
    SQL SP Return.vi ‏29 KB

    I finaly found what was wrong... It was necessary an only aditional line in the stored procedure. It should be like that:
    CREATE PROCEDURE [dbo].[TS_Teste] (@T057_S_NOMEMAQUINA VARCHAR(20), @STATUS INT OUTPUT, @ERRO NVARCHAR(500) OUTPUT)
    AS
    BEGIN    
      SET NOCOUNT ON;                                                                                               -- NEW LINE!!!
      DECLARE @TABLE TABLE(CODIGO INT, DESCRICAO VARCHAR(30))
      INSERT INTO @TABLE VALUES (51, 'A')    
      INSERT INTO @TABLE VALUES (52, 'B')
      INSERT INTO @TABLE VALUES (53, 'C')
      SELECT * FROM @TABLE
      SET @STATUS = 1
      SET @ERRO = 'Nenhum erro!'
      RETURN 0
    END

  • How do I get return parameters from a stored procedure call?

    The Open SQL Statement has an option on the Advanced tab to specify a command type of 'stored procedure'. In addition to returning a recordset, a stored procedure can also return parameters (see http://support.microsoft.com/support/kb/articles/Q185/1/25.ASP for info on doing this with ADO). Is it possible to get those return parameters with TestStand? In particular, I want to be able to get error codes back from the stored procedure in case it fails (maybe there is another way).

    The Open SQL Statement step type does not fully support stored procedures. If the procedure returns a record set than you can fetch the values as you would a SELECT statement. Stored procedures require you to setup the parameters before the call and this is not yet supported. Bob, in his answer, made a reference to the Statements tab and I think that he was talking about the Database Logging feature in TS 2.0.
    If the stored procedure is returning a return value, it may return as a single column, single row recordset which can be fetched as you normally do a record set.
    Scott Richardson
    National Instruments

  • ERROR WHILE INSERTING BLOBS AS PARAMETERS OF EXISTING STORED PROCEDURE

    I have 2 simple tables to keep large application data (as XMLDOCUMENT in one table and BLOB in another):
    SQL> desc bindata_tbl;
    Name Null? Type
    BDATA_ID NOT NULL NUMBER(10)
    BDATA NOT NULL BLOB
    SQL> desc metadata_tbl;
    Name Null? Type
    MDATA_ID NOT NULL NUMBER(10)
    MDATA NOT NULL SYS.XMLTYPE
    and stored preocedure to input new data into those tables:
    "SP_TEST_BIN_META_DATA"
    i_MetaData in METADATA_TBL.MDATA%TYPE,
    i_BinData in BINDATA_TBL.BDATA%TYPE
    as
    begin
    if i_MetaData is not null then
    insert into METADATA_TBL (MDATA_ID, MDATA)
    values (METADATA_SEQ.nextval, i_MetaData);
    end if;
    if i_BinData is not null then
    insert into BINDATA_TBL (BDATA_ID, BDATA)
    values (BINDATA_SEQ.nextval, i_BinData);
    end if;
    COMMIT;
    -- Handle exceptions
    EXCEPTION
    WHEN OTHERS THEN
    ROLLBACK;
    RAISE;
    end;
    I communicate with database from .Net application using "Oracle.DataAccess 10.1.0.200 (Runtime version v1.0.3705)" component.
    Following procesure is a [simplified] examlple of the code I use, which demonstrates the errors while inserting XMLDOCUMENT and BLOB values simultaneously.
    In my application those should be quite big objects (~200 K XML and ~5-25M binary image data), but following sample keeps failing even with very small-sized objects:
    Line Number
    1          private void PureTest()
    2          {
    3               OracleConnection conn = null;
    4               OracleTransaction tx = null;
    5               OracleCommand command = null;
    6
    7               try
    8               {
    9                    // Open connection
    10                    string strConn = "Data Source=AthenaWf; User ID=AthenaWf; Password=Poseidon";
    11                    conn = new OracleConnection( strConn );
    12                    conn.Open();
    13
    14                    // Begin transaction (not sure if really needed)
    15                    tx = conn.BeginTransaction();
    16
    17                    // Create command
    18                    string strSql = "SP_TEST_BIN_META_DATA";
    19                    command = new OracleCommand();
    20                    command.Connection = conn;
    21                    command.CommandText = strSql;
    22                    command.CommandType = CommandType.StoredProcedure;
    23
    24                    // Create parameters
    25                    // 1) XmlType parameter
    26                    string strXml = "<?xml version=\"1.0\"?><configuration testValue=\"123456789\"/>";
    27                    XmlDocument xmlDoc = new XmlDocument();
    28                    xmlDoc.LoadXml( strXml );
    29                    OracleXmlType oraXml = new OracleXmlType( conn, xmlDoc );
    30                    //oraXml = null;
    31                    //
    32                    OracleParameter xmlPrm = new OracleParameter();
    33                    xmlPrm.ParameterName = "i_MetaData";
    34                    xmlPrm.Direction = ParameterDirection.Input;
    35                    xmlPrm.OracleDbType = OracleDbType.XmlType;
    36                    xmlPrm.Value = oraXml;
    37                    command.Parameters.Add( xmlPrm );
    38
    39                    // 2) Blob type
    40                    byte[] buf = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    41                    OracleBlob oraBlob = new OracleBlob( conn, true );
    42                    //oraBlob.Write( buf, 0, buf.Length );
    43                    oraBlob = null;
    44                    //
    45                    OracleParameter blobPrm = new OracleParameter();
    46                    blobPrm.ParameterName = "i_BinData";
    47                    blobPrm.Direction = ParameterDirection.Input;
    48                    blobPrm.OracleDbType = OracleDbType.Blob;
    49                    blobPrm.Value = oraBlob;
    50                    command.Parameters.Add( blobPrm );
    51
    52
    53                    // Execute command finally
    54                    command.ExecuteNonQuery();
    55                    tx.Commit();
    56               }
    57               catch( Exception ex )
    58               {
    59                    // Clean-up
    60                    if( command != null )
    61                    {
    62                         command.Dispose();
    63                    }
    64                    if( tx != null )
    65                    {
    66                         tx.Dispose();
    67                    }
    68                    if( conn != null )
    69                    {
    70                         conn.Dispose();
    71                    }
    72
    73                    // Display error message
    74                    MessageBox.Show( ex.Message, "Error" );
    75               }
    76          }
    If I try insert only XMLDOCUMENT object (lines 30, 42 are commented out, 43 IS NOT) - everything is OK.
    If I try to insert only BLOB object (lines 30, 42 are NOT COMMENTED OUT, line 43 is commented out) - everything is OK again.
    If I try to insert them both having some values (lines 30, 43 are commented out, 42 is not commented out) - it fails right on "command.ExecuteNonQuery();" (line 54)
    with the following exception:
    "ORA-21500: internal error code, arguments: [%s], [%s], [%s], [%s], [%s], [%s], [%s], [%]".
    Even when I nullify oraBlob before assigning it to OracleParameter value (line 30 is commented out, line 42 and 43 are not) I have the same exception.
    XMLDOCUMENT and DLOB data logically are very coupled objects (in my application), so I really want to insert them simultaneously in one stored procedure in transactional way.
    Is it bug of drivers, server, .net environment, or I miss something in implementation?
    PS. In some articles on Oracle web and in MSDN site I found a mention about necessity of wrapping all write/update operations in a transaction, while working with temporary LOBs. I use it here, but it does not look like changing anything.

    Hello,
    I tested your code with the 10.1.0.4.0 ODP and 10.1.0.4.0 Client and it worked fine.
    Can you please apply the 10.1.0.4.0 patches for both ODP and client to see if this resolves the issue for you.
    Here is the output from the same execution of the ODP application you provided as a testcase. These rows were inserted at the same time when I executed the application and passed the data as parameters to the SP you provided.
    Results of Testing with 10.1.0.4.0
    ==========================
    SQL> select count(*) from BINDATA_TBL
    2 ;
    COUNT(*)
    1
    SQL> select count(*) from METADATA_TBL;
    COUNT(*)
    1
    SQL> select dbms_lob.getlength(bdata) from BINDATA_TBL;
    DBMS_LOB.GETLENGTH(BDATA)
    10
    SQL> select mdata from METADATA_TBL;
    MDATA
    <?xml version="1.0"?><configuration testValue="123456789" />

  • Passing Variable Number of Parameters to Cobol Stored Procedure

    Hi. I have a web front end that needs to access several different tables via Cobol stored procedures. It seems simple enough to call the stored procedures straight away (DAO Pattern perhaps?) but my boss is insistent on having an intermediate Cobol program that decides which table to access. I think he at a bigger picture than I can see.
    The problem lies in the number of parameters that need to be passed to the stored procedures; some need 3, others needs 5, a few need 4. The only two solutions that I can think of are to pass EVERYTHING (we're talking 50 parameters or so) to the intermediate stored procedure and then pulling only what is needed from that data set to access the desired table. Solution number two involves passing everything to a temp table and then pulling what is needed from it. The former solution seems a little cleaner but still involves passing a lot of parameters. If Cobol could handle some sort of dynamic memory allocation (Vector) there seems to be a possible solution there. Though, as far as I know, that isn't possible.
    Any ideas are much appreciated.
    Thanks in advance,
    Chris

    Hi Saurabh,
    The method in which stored procedures are called on form submit is something as follows.
    Let us take your scenario of a form which has multiple checkboxes and a submit button. On clicking the submit button, this form data is submitted using either get or post. The form's submit action invokes a procedure.
    The HTML form code will look something like this..
    htp.formOpen( curl => 'URL /myProcedure',
    cmethod => 'post' );
    htp.formCheckbox( cname => 'myCheckbox'
    cvalue => 'A');
    htp.formCheckbox( cname => 'myCheckbox'
    cvalue => 'B');
    htp.formCheckbox( cname => 'myCheckbox'
    cvalue => 'C');
    htp.formSubmit( cname => 'myButton',
    cvalue => 'OK');
    Now, whenever the submit button is clicked, all these form values are passed to our stored procedure 'myProcedure'.
    "myProcedure" looks something like this.
    procedure myProcedure
    myCheckbox IN sys.owa_util.vc_arr,
    myButton IN VARCHAR2
    is
    begin
    end myProcedure;
    The point to be noted here is that the name of the variable being passed in the procedure is the same as the name of the HTML element being created in the HTML form. So, there is a direct mapping between the elements in the HTML form and the procedure parameters.
    Another noteworthy point is that since you have multiple checkboxes in your HTML form, it is impractical to name all the checkboxes differently and then pass those many parameters to your procedure (Imagine a scenario where there are a hundred check-boxes in an HTML form!). So portal allows you to give the same name (cname) to all the checkboxes in your HTML form, and if multiple checkboxes are checked, it will return all the checkbox values in an array (Note the usage of "myCheckbox IN sys.owa_util.vc_arr" in myProcedure).
    You can check out this link for more information.
    Re: retrieving data from fields
    Thanks,
    Ashish.

  • Problem in calling nested stored procedure

    Hi,
    I am using execute(), getMoreResults() and getResultSet() methods to call sybase stored proc. It is working fine when calling a simple stored proc. But it is giving following error when this stored proc calls another stored proc inside it.
    <<
    Error connecting: com.sybase.jdbc2.jdbc.SybSQLException: Implicit conversion from datatype 'INT' to 'CHAR' is not allowed. Use the CONVERT function to run this query
    >>
    It will be very helpful if somebody shares the experience of nested stored procs calls using JDBC.
    -Subhendu

    Vinay,
    Thanks for replying...
    Following is the excerpts from the parent procedure
    create proc TEST_PARENT_sp
    (@fundID char(5) = NULL)
    as
    begin
    exec TEST_CHILD_sp @fundID
    end
    The code for CHILD proc is attached
    create procedure TEST_CHILD_sp
    (@fundID char(5) = NULL)
    as
    begin
    insert #PV_funds_curr
    (fundID,
    curr_id,
    curr_type,
    tcurr_id,
    in_xrate_id,
    out_xrate_id,
    display_seq)
    select
    pv.fund_id,
    rl.curr_id,
    rl.curr_type,
    rl.curr_id,
    null,
    null,
    pv.display_seq
    from
    #PV_funds pv,
    RL_currencies rl,
    #PV_currencies tmp_c
    where
    @fundID in (pv.fund_id, 'ALL') and
    pv.fund_id = rl.fund_id and
    tmp_c.curr_id in (rl.curr_id, 'ALL') and
    tmp_c.curr_type in (rl.curr_type, 'ALL')
    end
    Regards,
    Subhendu.
    PS.- The Parent Stored proc works fine while calling from other applications,e.g., Rapid SQL, isql.

  • Picking up Parameters in a Stored Procedure

    Hi,
    Using the following sqlplus call I am executing a sql script.
    sqlplus username/password @test.sql "TEST1" "TEST2"
    The test.sql script makes the following call:
    execute TABLEOWNER.TEST_SP;
    Can anyone tell me how to pass parameters shown in the sqlplus call to the execute command so that they are available to the stored procedure?
    And then how do I pick those two parameter values up in the stored procedure?
    I have a procedure created using the following syntax, but when I try to create the procedure using this syntax I get prompted for a value for 1, and then for 2, the procedure then creates without any errors but when I check the definition for the procedure I can see that rather then the &1 and &2 parameters, they have been replaced with whatever I enter for 1 and 2 when the procedure was created.
    CREATE OR REPLACE PROCEDURE TEST_SP AS
    --Declare and initialise variable passed from shell script
    lvBATCH_ID VARCHAR2(10) := '&1';
    lvCREATED_DATE VARCHAR2(6) := '&2';
    Thanks.

    The procedure will just be passed parameters as normal. It doesn't care what calls it:
    CREATE OR REPLACE PROCEDURE test_sp
        ( p1 VARCHAR2, p2 VARCHAR2 )
    AS
    BEGIN
        DBMS_OUTPUT.PUT_LINE(p2 || ', ' || p1);
    END test_sp;Your SQL*Plus script would contain something like:
    exec test_sp('&1','&2')(the single quotes being required for character literals in this example - you wouldn't need them for numeric values)
    You would call the SQL*Plus script as
    @test_script World Hello

  • 10.2.0.3 driver. Maximum limit of parameters in a stored procedure

    What is the Maximum limit of parameters that can be passed to a stored procedure via ODBC? We got a function that was executed successfully by the 9i driver with 272 parameters. The same function fails when executed with 10.2.0.3 driver with ORA-06513 error. We then tried reducing the parameters and found that the driver would allow a maximum of 253 parameters. Any ideas or thoughts on this is much appreciated.

    Update for future reference:
    Finally got a metalink account and ran with the latest instantclient patch. This seemed to stop the heap corruption problem.

  • Using VARRAYs as parameters to a Stored Procedure

    I'm trying to pass a VARRAY as an IN/OUT parameter into a simple stored procedure by doing the following ..
    call.addNamedInOutputArgument(.., .., .., oracle.sql.ARRAY.class);
    I'm using a DataReadQuery. I set the call in the query, bind all parameters and add the IN/OUT argument to the query (i.e. query.addArgument(<name>)). Then I create an oracle.sql.ArrayDescriptor to describe the ARRAY.
    ArrayDescriptor ad = ArrayDescriptor.createDescriptor(<name of VARRAY>, <connection>);
    The VARRAY is of size 1 whose type is INTEGER. I create an ARRAY of Integer objects.
    Integer fields[1] = new Integer[1];
    fields[0] = new Integer(2);
    ARRAY a = new ARRAY(ad, <connection>, fields);
    I create a Vector of parameters and add the ARRAY to it. Then I execute the query ..
    Object result = session.executeQuery(<query>, <Vector>);
    When I execute the query I keep getting an ORA-06550: wrong number or types of arguments in call to <stored procedure>. Any help would be appreciated. Thanks. -Michael-

    The workaround above using JDBC directly to call store procedures using VARRAY types is still probably your best solution.
    In TopLink 10.1.3 there is a new API on StoredProcedureCall that allows passing the JDBC type code which should allow binding of VARRAY output parameters.
    addNamedInOutputArgument(String procedureParameterName, String inArgumentFieldName, String outArgumentFieldName, int type, String typeName) {                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Nested Stored procedure

    Hi experts,
    case :- A stored procedure calling 5 stored procedure in 3rd procedure a error handled in execption
    is the 3rd procedure resume next?
    the 4 & 5 procedure will execute or not?
    Many thanks
    Kalinga

    Hi experts,
    case :- A stored procedure calling 5 stored procedure
    in 3rd procedure a error handled in execption
    is the 3rd procedure resume next?
    the 4 & 5 procedure will execute or not?
    Many thanks
    KalingaSo you have 1 procedure that calls 5 others.
    In the 3rd procudure an exception happens, which you capture within that procedure and handle it.
    Assuming the 3rd procedure exception handler is at the top level for that procedure, it will cease execution and drop back out and then the 4th and 5th procedures will continue to be executed.
    If the exception handler in the 3rd procedure is in a nested execution block then the execution will continue from after that execution block in that 3rd procedure.
    If the 3rd procedure doesn't actually handle the exception but raises the error then the exception handler of the calling procedure will capture the exception (if there is an exception handler there) and the 4th and 5th procedures will not be called.
    The key thing to remember is that once an exception happens inside an execution block the execution point cannot return back within that same execution block automatically. It can only leave that execution block gracefully by handling the exception or it can raise the exception up a level to the calling execution block's exception handler.

  • Maximum number of parameters sent to stored procedure

    I have a web form from where I insert data to Oracle. There are at least 20 fileds on the form. For INSERT I want to use Stored Procedure. But in this case for VALUES section of the INSERT statement I need to send that many- in this case 20 parameters. Is this normal for a procedure to receive 20 parameters? If it's not, then what way should I follow to perform this? I know technically there's no problem but is this normal programming or database managementwise? I think this is the basic thing all web developer do all the time.

    He's got 20 fields on a web form and you think using SQL*Loader is a good idea ?because I do not believe that he has to enter these fields once time.
    You want him to write the values to a flat file, generate a control file, then invoke SQL*Loader ?I know that the first time you create all those files can be a problem, but when you have all , the next times its just change the information into flat file.
    Did you read the question ?Yes, i did
    It's only my opinion, He can accept it or not.
    any other question not related to help him to solve his problem?

  • How to add parameters to a stored procedure in B1 Query generator

    Dear All,
    I made a stored procedure in sql. I'd like to call it from B1. It's working fine when I call like this (I created an empty query in Query generator and paste this) :
    exec stproc  @projectFrom = '',
                       @projectTo = 'PRJ03',
                       @profitCodeFrom = '',
                       @profitCodeTo = 'uj',
    The problem is, Could I call this procedure with parameters like normal queries (select ... where .. = [%0])? Can I pass parameters to it somehow?
    Thanks a lot
    Jani

    Inside B1 :
    DECLARE @return_value int
    Declare @Fromdate datetime
    declare @Todate datetime
    declare @supp nvarchar(15)
    SELECT * FROM OINV T0 INNER JOIN INV1 T1 ON T0.DocEntry = T1.DocEntry where
    T0.cardcode = '%Supp' and T0.DocDate <=%FromDate
    and T0.DocDate >=%ToDate
    EXEC @return_value=SQL2XMLforINV
    @Fromdate= %FromDate,
    @ToDate= %ToDate,
    @Supp = '%Supp'
    SELECT 'Return Value' = @return_value
    And in SQL I have a stored procedure :
    Starting like this :
    PROCEDURE [dbo].[SQL2XMLforINV]
    @Fromdate datetime,
    @Todate datetime,
    @supp nvarchar(15)
    AS
    DECLARE @bcpCommand AS varchar(3000)
    declare @base nvarchar(50)
    BEGIN
         SET NOCOUNT ON;
    And my error message is in B1 ....
    Thanks in advance for your help ....

  • Java and Sybase nested stored procedures.

    Hi!
    I have nested Sybase stored procedures, the main procedure calls a helper stored proc.
    The main procedure returns 2 result sets before calling the helper store proc and helper store proc returns 1 resultset. After the helper store proc is called, the main store proc returns 2 more resultset. When I run it using SQL client tool the main procedure(and it's helper) execute well and returns rows.
    I need to call this store proc in a java code and display all the resultset in screen. I am using Statement:execute(<exec sp>) to execute the store proc and then statement.getResultSet() to get each resultset. The loop is controlled by statement.getMoreResults() .
    It displays the first 2 resultsets from main Store Proc. Then the control goes to helper store proc. It executes the helper store proc and displays the resultset from helper. But then it stops there and doesnot
    come back to main store proc to execute the remaining resultset.
    What I suspect is that, the statement object is getting overlaid when the call goes to helper proc.
    Any idea as to how to code to handle multiple nested resultset ?
    ~ RNS.
    My Sybase stored procedure code looks like -
    =======================================================================
    create procedure main_proc
    @param1 int
    as
    select getdate()
    select @@servername
    declare @return_val int
    exec proc2 @param1, @return_val out
    select myCol1,
    myCol2,
    myCol3=@return_val
    from mytable
    select db_name()
    ===========================================================================
    Sybase Code for proc2
    create procedure proc2
    @param1 int,
    @param2 int out
    as
    begin
    if something exists(select * from table where whereClause)
    select @param2="TRUE"
    else
    select @param2="FALSE"
    select getdate()
    end
    go
    GRANT EXECUTE...
    EXEC sp_procxmode 'dbo.proc2,'unchained'
    go
    ====================================================================
    Code snippet :-
    do {
    int iit=0;
    rs=stmt.getResultSet();
    if ( rs != null ) {
    ResultSetMetaData rsd = rs.getMetaData();
    int nocols = rsd.getColumnCount();
    for (int i=1; i<=nocols; i++)
    System.out.println(rsd.getColumnName(i)));
    while (rs.next())
    for (int i=1; i<=nocols; i++)
    System.out.println(rs.getString(rsd.getColumnName(i));
    } while (stmt.getMoreResults());

    I'm not 100% sure about this, but my guess is that this is caused by the TDS protocol (used by Sybase). TDS makes no difference between the stored procedure you are calling and the "inner" stored procedure, so the driver just returns update counts and result sets as they are generated, regardless of who generated them.
    Another guess (as I don't know what driver you are using) is that execute() returns the first result (update count or ResultSet), as opposed to executeQuery(), which returns the first ResultSet (probably discarding the update count). You can make sure of this by calling getMoreResults(); you should get your ResultSet at some point.
    Alin.

  • How I ca have the name of parameters of  an stored procedure?

    Hi,
    I have an stored procedure with a lot of parameters. I want to list them automatically by writing codes to show me the name of all parameters
    thanks,
    mandana

    Back to your original question... it's a bit hard to answer this without you saying what DB system you're using, as the answer will be different depending on the system.
    Actually one can do it with JDBC easily enough, so the solution would be DB-independent.
    Have a look at this: http://java.sun.com/javase/6/docs/api/java/sql/DatabaseMetaData.html, specifically http://java.sun.com/javase/6/docs/api/java/sql/DatabaseMetaData.html#getProcedures(java.la ng.String,%20java.lang.String,%20java.lang.String) and http://java.sun.com/javase/6/docs/api/java/sql/DatabaseMetaData.html#getProcedureColumns(j ava.lang.String,%20java.lang.String,%20java.lang.String,%20java.lang.String).
    I did have some proof-of-concept code for this at some stage, but I cannae find it now, sorry.
    Adam

Maybe you are looking for