Add Table Valued Parameter to a stored procedure

I have a stored procedure that voids an invoice and puts the items back into inventory and makes available the payment that was used to apply to this invoice... I would like to be able to do all this for a number of invoices at a time using a table valued
parameter how would I be able to do it?
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Debra
-- Create date: March 25, 2014
-- Description: Void an invoice.
-- =============================================
CREATE PROCEDURE AR_VOID
-- Add the parameters for the stored procedure here
@Invoice INT,
@InvType nvarchar(3)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
    -- Insert statements for procedure here
IF(@InvType = 'reg')
    BEGIN
UPDATE INV SET ONHAND = ONHAND + ARD.Qty ,STAMPED = CASE WHEN INV.TYPE = 'CIG' THEN STAMPED + ARD.QTY ELSE 0 END, LASTDATE = CONVERT(DATE, GETDATE()) FROM ARD JOIN INV ON ARD.ITEM = INV.ITEM
WHERE ARD.INVOICE = @Invoice
MERGE INTO RECEIPTSH target
    USING (SELECT JOURNAL, SUM(AMOUNT) AMOUNT FROM Applied
    WHERE INVOICE = @Invoice GROUP BY JOURNAL) AS source
    ON target.Journal = source.Journal
    WHEN MATCHED THEN 
    UPDATE 
    SET Applied = Applied - SOURCE.Amount;
    DELETE Applied WHERE INVOICE = @Invoice
    END
    ELSE 
    BEGIN
UPDATE INV SET ONHAND = ONHAND - ARD.Qty ,STAMPED = CASE WHEN INV.TYPE = 'CIG' THEN STAMPED - ARD.QTY ELSE 0 END, LASTDATE = CONVERT(DATE, GETDATE()) FROM ARD JOIN INV ON ARD.ITEM = INV.ITEM
WHERE ARD.INVOICE = @Invoice
MERGE INTO ARH target
    USING (SELECT INVOICE, SUM(AMOUNT) AMOUNT FROM CREDITMEMO WHERE CINVOICE = @Invoice GROUP BY INVOICE) AS source
    ON target.INVOICE = source.INVOICE
    WHEN MATCHED THEN 
    UPDATE 
    SET [OPEN] = 'TRUE', CLOSEDATE = NULL, PAID = target.PAID - source.AMOUNT;
DELETE CREDITMEMO WHERE CINVOICE = @Invoice
    END
    UPDATE ARH SET SUBTOTAL = 0, TAXES = 0, PAID = 0, STATUS = 'VOD', [OPEN] = 'FALSE', CLOSEDATE = CONVERT(DATE,GETDATE()) WHERE INVOICE = @Invoice
UPDATE ARD SET QTY = 0, ARD.PRICE = 0 WHERE INVOICE = @Invoice
END
GO
Debra has a question

Try
CREATE TYPE InvoicesList AS TABLE (InvoiceID INT)
GO
- =============================================
-- Author: Debra
-- Create date: March 25, 2014
-- Description: Voids passed invoices.
-- =============================================
CREATE PROCEDURE AR_VOID
@InvoicesList InvoicesList READONLY,
@InvType nvarchar(3)
AS
BEGIN
SET NOCOUNT ON;
IF(@InvType = 'reg')
BEGIN
UPDATE INV SET ONHAND = ONHAND + ARD.Qty ,STAMPED = CASE WHEN INV.TYPE = 'CIG' THEN STAMPED + ARD.QTY ELSE 0 END, LASTDATE = CONVERT(DATE, GETDATE()) FROM ARD JOIN INV ON ARD.ITEM = INV.ITEM
WHERE ARD.INVOICE IN (SELECT InvoiceID FROM @InvoicesList)
MERGE INTO RECEIPTSH target
USING (SELECT JOURNAL, SUM(AMOUNT) AMOUNT FROM Applied
WHERE INVOICE IN (SELECT InvoiceID FROM @InvoicesList) GROUP BY JOURNAL) AS source
ON target.Journal = source.Journal
WHEN MATCHED THEN
UPDATE
SET Applied = Applied - SOURCE.Amount;
DELETE Applied WHERE INVOICE IN (Select InvoiceID FROM @InvoicesList)
END
ELSE
BEGIN
UPDATE INV SET ONHAND = ONHAND - ARD.Qty,STAMPED = CASE WHEN INV.TYPE = 'CIG' THEN STAMPED - ARD.QTY ELSE 0 END, LASTDATE = CONVERT(DATE, GETDATE()) FROM ARD JOIN INV ON ARD.ITEM = INV.ITEM
WHERE ARD.INVOICE IN (SELECT InvoiceID FROM @InvoicesList)
MERGE INTO ARH target
USING (SELECT INVOICE, SUM(AMOUNT) AMOUNT FROM CREDITMEMO WHERE CINVOICE IN (SELECT InvoiceID FROM @InvoicesList) GROUP BY INVOICE) AS source
ON target.INVOICE = source.INVOICE
WHEN MATCHED THEN
UPDATE
SET [OPEN] = 'TRUE', CLOSEDATE = NULL, PAID = target.PAID - source.AMOUNT;
DELETE CREDITMEMO WHERE CINVOICE IN (SELECT InvoiceID FROM @InvoicesList)
END
UPDATE ARH SET SUBTOTAL = 0, TAXES = 0, PAID = 0, STATUS = 'VOD', [OPEN] = 'FALSE', CLOSEDATE = CONVERT(DATE,GETDATE()) WHERE INVOICE IN (SELECT InvoiceID FROM @InvoicesList)
UPDATE ARD SET QTY = 0, ARD.PRICE = 0 WHERE INVOICE IN (SELECT InvoiceID FROM @InvoicesList)
END
GO
I didn't look too close into your code, so I just translated your code as is into TVP.
For every expert, there is an equal and opposite expert. - Becker's Law
My blog
My TechNet articles

Similar Messages

  • Passing Multi-Value Parameter to a Stored Procedure

    Has anyone experienced passing a Parameter (MultiValue) to a Stored Procedure? I am aware that Crystal Passes the Param as an Array. How would you go about handling this within a Stored Procedure???

    Hi Daniel
    Try as below:
    1. Create a Crystal report, and add a multi-value parameter.
    2. Since the multi-value parameter is treated as an array, create a formula that uses the JOIN function. Create a formula as below:
    //Formula: @JoinFormula
    Join ({?Multi-value parameter array},";")
    ====================
    NOTE:
    In the formula above, a semi-colon (";") is the delimiter.
    ====================
    3. Within the main report, create a subreport based on the stored procedure, and include the parameter to be populated with the multi-value list.
    4. Link the Join formula in the main report to the stored procedure parameter in the subreport.
    Doing so passes a multi-value parameter to the stored procedure.
    Hope this helps!!!!
    Regards
    Sourashree

  • Would like to pass multi-value parameter to a stored procedure

    Hi,
    Is it possible to pass a multi-value parameter to a stored procedure using crystal reports.
    Is there is a way to do so??/
    Thanks,
    Brian.

    Hi,
    Is it that you want to pass 2 or more parameters to a stored proc. it is possible
    go to database expert
    select your connection and click on add command their you will have to create parameters and pass to a proc
    for ref..
    {CALL `menagerie`.`sp_timer`({?delay time},{?delay time2})}
    where `menagerie`.`sp_timer` is a stored proc.
    and delay time and delay time2 are  parameters.
    but if it is like you have to pass multiple values to stored proc using single parameter as per my experience its
    not possible.

  • How to pass a table as parameter on a stored procedure

    Hello all,
    I want to pass the name of a table as parameter into a stored procedure, that will be used for cursors etc.
    But when i pass the parameter and i compile the S.P. it give me error (error: table not existing...)
    Any Help?
    Thanks in advance, Marco

    Marco wrote:
    As i've written above, i'm using stored procedures like 'batch' programs which will be executed with oracle scheduler (passing to s.p. the name of the 'input' tables)
    These input tables are 'external' tables which have got the same structure; for example i've got TABLEX_001, TABLEX_002, XXTAB etc. with the same structure.
    This is the the reason... what do you think?An external table definition can reference multiple files via the LOCATION definition or you can user "ALTER TABLE" to alter the location and change the file that the external table points to.
    Thus you only need one static External Table and use an alter table (via execute immediate) to change the file location it points to, or if you want all the data together, just specify all the files in the location.
    That would be clean design, using one fixed table, without the need to pass any table names, just dynamically altering the file names if necessary at run time.

  • CR XI - Pass a Multi-value Parameter to a Stored Procedure

    Hello,
    Here is my problem !
    My Main Report accept a Multi-value Parameter "myParameter".
    I create a formula "lstParameter" (Join({?myParameter},',')  linked to my SubReport (string static parameter based on a Stored Procedure  which returns a RefCursor (ORACLE)).
    When I launch the Main Report, he is blank...but if I open the subreport in the overview i can see the result...
    it seems like the MainReport don't call the SubReport, or something like that...
    I hope you can help me !
    Thanks
    Anthony
    Edited by: anthony.44 on Jan 12, 2012 4:53 PM
    Edited by: anthony.44 on Jan 13, 2012 9:51 AM

    hello,
    I resolve my problem....just inside into the detail of the Master report a result of a query (ex: select sysdate from dual)...and the sub report is called correctly

  • Whats the difference betweeen passing the table variable and table valued parameter?

    Hi Everbody
      Can someone one tell me what's the difference between passing a table variable and table valued parameter to a stored procedure or function? Can both be used to pass a table to a stored procedure/function?
    Regards
    Regards

    They are essentially the same. What we call a table variable is a local
    variable. A table-valued parameter is an incoming parameter to the
    procedure. The only difference is that the parameter is readonly.
    When you call a stored procedure, you can pass a table variable as the
    actual parameter. Or a table-valued parameter that you pass on.
    CREATE PROCEDURE nisse_sp @tvp sometype READONLY AS
    DECLARE @local someothertabletype
    EXEC pelle_sp @tvp, @local
    Erland Sommarskog, SQL Server MVP, [email protected]

  • How to change stored procedure with Table Valued Parameter

    I am not sure how to change the normal stored procedure with Table Value Parameter.Do I have to create a separate Table or do I have to create a datatype. Can you please help me with this
    ALTER PROCEDURE [dbo].[uspInsertorUpdateINF]
    @dp_id char(32),
    @dv_id char(32),
    @em_number char(12),
    @email varchar(50),
    @emergency_relation char(32),
    @option1 char(16),
    @status char(20),
    @em_id char(35),
    @em_title varchar(64),
    @date_hired datetime
    AS
    BEGIN
    SET NOCOUNT ON;
    MERGE [dbo].[em] AS [Targ]
    USING (VALUES (@dp_id, @dv_id , @em_number, @email, @emergency_relation, @option1, @status, @em_id, @em_title, @date_hired))
    AS [Sourc] (dp_id, dv_id, em_number, email, emergency_relation, option1, status, em_id, em_title, date_hired)
    ON [Targ].em_id = [Sourc].em_id
    WHEN MATCHED THEN
    UPDATE
    SET dp_id = [Sourc].dp_id,
    dv_id = [Sourc].dv_id,
    em_number = [Sourc].em_number,
    email = [Sourc].email,
    emergency_relation = [Sourc].emergency_relation,
    option1 = [Sourc].option1,
    status = [Sourc].status,
    em_title = [Sourc].em_title,
    date_hired = [Sourc].date_hired
    WHEN NOT MATCHED BY TARGET THEN
    INSERT (dp_id, dv_id, em_number, email, emergency_relation, option1, status, em_id, em_title,date_hired)
    VALUES ([Sourc].dp_id, [Sourc].dv_id, [Sourc].em_number, [Sourc].email, [Sourc].emergency_relation, [Sourc].option1, [Sourc].status, [Sourc].em_id, [Sourc].em_title, [Sourc].date_hired);
    END;

    It's not clear how you would change the procedure. But assuming that you want to replace the existing scalar parameters with tabular input, this is how you would do it. You first create a table type:
    CREATE TYPE  Insertor_type AS TABLE
        (dp_id                char(32),
         dv_id                char(32),
        em_number            char(12),
        email                varchar(50),
        emergency_relation   char(32),
        option1              char(16),
        status               char(20),
        em_id                char(35),
        em_title             varchar(64),
        date_hired           datetime)
    Then you change the procedure header:
    ALTER PROCEDURE [dbo].[uspInsertorUpdateINF] @tvp Insertor_type READONLY AS
    And finally you change the USING clause:
       USING (SELECT dp_id, dv_id , em_number, email, emergency_relation, option1, status, em_id, em_title, date_hired
              FROM   @tvp) AS [Sourc] ON [Targ].em_id = [Sourc].em_id
    The rest is fine as it is.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Selecting multiple rows a table according to rows passed with a table valued parameter

    Ive got a table, which looks like this:
    CREATE TABLE MyTable (
    MyChars CHAR(3) NOT NULL,
    MyId INT NOT NULL,
    CONSTRAINT PK__MyTable_MyChars_MyId PRIMARY KEY (MyChars, MyId),
    CONSTRAINT FK__MyOtherTable_Id_MyTable_MyId FOREIGN KEY (MyId) REFERENCES MyOtherTable (Id)
    Records look like i.e.:
    Chars | Id
    'AAA' | 1
    'BBB' | 1
    'CCC' | 1
    'AAA' | 2
    'BBB' | 2
    'CCC' | 2
    'DDD' | 2
    'EEE' | 3
    'FFF' | 3
    'AAA' | 4
    'DDD' | 4
    'FFF' | 4
    Now I have a SP, which takes a table valued parameter like:
    CREATE TYPE dbo.MyTVP AS TABLE ( MyChars CHAR(3) )
    This SP should return a set of Ids, which match all the rows of the parameter.
    I.e.:
    if the TVP contains 'AAA', 'BBB' & 'CCC', i get as result 1 & 2
    if the TVP contains 'AAA' & 'FFF', i get as result 4
    if the TVP contains 'BBB' & 'EEE', i get an empty result
    What my SP is currently doing, is to build a query with string concatination, which is then executed with the EXEC statement. If we take my first example, the built query would look like this:
    SELECT DISTINCT t0.MyId
    FROM MyTable t0
    INNER JOIN MyTable t1 ON t0.MyId = t1.MyId
    INNER JOIN MyTable t2 ON t1.MyId = t2.MyId
    WHERE t0.MyChars = 'AAA' AND t1.MyChars = 'BBB' AND t2.MyChars = 'CCC'
    It works, but I'm not very fond of building the query. Maintaining such things is always a pain. And it also might not be the most efficient and elegant way to do this.
    Since I can't think of any other way of doing this, I wanted to ask, if someone of you got an idea, if there is a better way to accomplish this.

    Let me give you a "cut and paste" I use in the SQL Server groups:
    1) The dangerous, slow kludge is to use dynamic SQL and admit that any random future user is a better programmer than you are. It is used by Newbies who do not understand SQL or even what a compiled language is. A string is a string; it is a scalar value like
    any other parameter; it is not code. Again, this is not just an SQL problem; this is a basic misunderstanding  of programming principles. 
    2) Passing a list of parameters to a stored procedure can be done by putting them into a string with a separator. I like to use the traditional comma. Let's assume that you have a whole table full of such parameter lists:
    CREATE TABLE InputStrings
    (keycol CHAR(10) NOT NULL PRIMARY KEY,
     input_string VARCHAR(255) NOT NULL);
    INSERT INTO InputStrings 
    VALUES ('first', '12,34,567,896'), 
     ('second', '312,534,997,896'),
     etc.
    This will be the table that gets the outputs, in the form of the original key column and one parameter per row.
    It makes life easier if the lists in the input strings start and end with a comma. You will need a table of sequential numbers -- a standard SQL programming trick, Now, the query, 
    CREATE VIEW ParmList (keycol, place, parm)
    AS
    SELECT keycol, 
           COUNT(S2.seq), -- reverse order
           CAST (SUBSTRING (I1.input_string
                            FROM S1.seq 
                             FOR MIN(S2.seq) - S1.seq -1) 
             AS INTEGER)
      FROM InputStrings AS I1, Series AS S1, Series AS S2 
     WHERE SUBSTRING (',' + I1.input_string + ',', S1.seq, 1) = ','
       AND SUBSTRING (',' + I1.input_string + ',', S2.seq, 1) = ','
       AND S1.seq < S2.seq
     GROUP BY I1.keycol, I1.input_string, S1.seq;
    The S1 and S2 copies of Series are used to locate bracketing pairs of commas, and the entire set of substrings located between them is extracted and cast as integers in one non-procedural step. The trick is to be sure that the right hand comma of the bracketing
    pair is the closest one to the first comma. The relative position of each element in the list is given by the value of "place", but it does a count down so you can plan horizontal placement in columns. 
    This might be faster now:
    WITH Commas(keycol, comma_seq, comma_place)
    AS
    (SELECT I1.keycol, S1.seq,
    ROW_NUMBER() OVER (PARTITION BY I1.keycol ORDER BY S1.seq)
    FROM InputStrings AS I1, Series AS S1
    WHERE SUBSTRING (',' || I1.input_string || ',' 
    FROM S1.seq 
    FOR 1) = ',' 
    AND S1.seq <= CHARLENGTH (I1.input_string))
    SELECT SUBSTRING(',' || I1.input_string || ','
    FROM C1.comma_place +1
    FOR C2.comma_place - C1.comma_place - 1)
    FROM Commas AS C1, Commas AS C2
    WHERE C2.comma_seq = C1.comma_seq + 1 
    AND C1.keycol = C2.keycol;
    The idea is to get all the positions of the commas in the CTE and then use (n, n+1) pairs of positions to locate substrings. The hope is that the ROW_NUMBER() is faster than the GROUP BY in the first attempt. Since it is materialized before the body of
    the query (in theory), there are opportunities for parallelism indexing and other things to speed up the works. 
    Hey, I can write kludges with the best of them, but I don't. You need to at the very least write a routine to clean out blanks, handle double commas and non-numerics in the strings, take care of floating point and decimal notation, etc. Basically, you must
    write part of a compiler in SQL. Yeeeech!  Or decide that you do not want to have data integrity, which is what most Newbies do in practice altho they do not know it. 
    A procedural loop is even worse. You have no error checking, no ability to pass local variables or expressions, etc. 
    CREATE PROCEDURE HomemadeParser(@input_string VARCHAR(8000))
    AS
    BEGIN
    DECLARE @comma_position INTEGER;
    CREATE TABLE #Slices
    (slice_value INTEGER);
    SET @input_string = @input_string + ','; --add sentinel comma
    SET @comma_position = CHARINDEX(',', @input_string); 
    WHILE @comma_position > 1
      BEGIN
      INSERT INTO #Slices (slice_value)
      VALUES(CAST(LEFT(@input_string, (@comma_position - 1)) AS INTEGER)); 
      SET @input_string = RIGHT(@input_string, LEN(@input_string)-@comma_position)
      SET @comma_position = CHARINDEX(',', @input_string)
      END;
    END;
    Better answer:
    http://www.simple-talk.com/sql/learn-sql-server/values()-and-long-parameter-lists/
    http://www.simple-talk.com/sql/learn-sql-server/values()-and-long-parameter-lists---part-ii/
    Do this with a long parameter list. You can pass up to 2000+ parameters in T-SQL, which is more than you probably will ever need. The compiler will do all that error checking that the query version and the procedural code simply do not have unless you write
    a full parser with the standard error codes. You can now pass local variables to your procedure; you can pass other data types and get automatic conversions, etc. In short, this is just good software engineering. 
    CREATE PROCEDURE LongList
    (@p1 INTEGER = NULL,
     @p2 INTEGER = NULL,
     @p3 INTEGER = NULL,
     @p4 INTEGER = NULL,
     @p5 INTEGER = NULL)
      x IN (SELECT parm
              FROM (VALUES (@p1), (@p2), (@p3), (@p4), (@p5)) AS X(parm)
            WHERE parm IS NOT NULL;
    You get all the advantages of the real compiler and can do all kinds of things with the values. 
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • How to pass the parameter of a stored procedure to iReport

    Hi... i don't know how to pass the parameter of the stored procedure to the iReport.
    In the Report Query, i tried
    1. sp_storedprocedure ' value'
    2. sp_storedprocedure +''''+$P{parameter}+''''+
    3. sp_storedprocedure +$V+$P{parameter}++$F($F is a variable having a value of ' (a single quote))may you enlighten us please? thank you

    For M$ SQL server I find that it only works when U use the fully qualified name...
    e.g. catalod.dbo.my_procedure_name 'variable'
    My full query in the Report Query window is something like this:
    EXEC arc.dbo.jasper_Invoice 1000
    Note that you may find that selecting from VIEWS / TABLES fails for no apparent reason and iReport will prompt you with the usual very unhelpful (we have what we "pay" for) prompt, stating that "The document is empty".
    To work around this issue, where a statement like "SELECT * FROM arc.dbo.acc_invoices WHERE Invoice_id=1000" does not work, simply create a PROC, something like:
    CREATE PROC jasper_MyProc (@my_rec_id integer) AS
    SELECT * FROM arc.dbo.acc_invoices WHERE Invoice_id= @my_rec_id integer
    ...to wrap your SELECT statement, then call the PROC
    Edited by: Sylinsr on Apr 22, 2008 4:23 PM

  • Set Null as Default  for input parameter to a stored procedure

    hi ,
    How can we set default values as NULL to an input parameter in a stored Procedure.
    create or replace procedure emp_proc ( p_test_input in varchar2
                                                        p_emp_id in number,
                                                        p_emp_name in varchar2,
                                                       p_manager_id in number )
    as
      begin
       if ( upper ( p_test_input ) = 'I' )
       then
          insert into emp
          values      ( p_emp_id  ,p_emp_name ,p_Manager_id,sysdate );
       elsif ( upper ( p_test_input ) = 'D' )
       then
          delete from emp
          where       emp_id  = p_emp_id;
       else
          dbms_output.put_line
             ( 'Please input ''A'' for ADD or ''D'' Delete  EMPLOYEE'
       end if;
    end;As Shown above if i want to do only delete operation
    i want to call this procedure like without passing extra parameters .
    EXECUTE  emp_proc('D',1010);Edited by: Rede on May 28, 2010 12:21 PM
    Edited by: Rede on May 28, 2010 12:22 PM

    create or replace procedure emp_proc ( p_test_input in varchar2,
                                                        p_emp_id in number,
                                                        p_emp_name in varchar2 default null,
                                                       p_manager_id in number default null )

  • Pass a datarow as input parameter in a stored procedure

    Hi everyone!
    I wonder if anyone know how to pass a datarow (better if tipized like "tablenameRow") as input parameter for a stored procedure.
    links or suggestions are welcome! (i'm newbie in .net programming, so if you can post some code i'll be really grateful!)
    Thank you!

    Hi,
    YES!! its possible you can pass a datarow to a SP from your Dot net application.
    Here below i'm going to give you an example for Desktop Application.
    For Passing a datarow as Input Parameters, your SP need to support for all these parameters.
    I mean, if a data row has 03 Columns. Then your procedure should be able to take 03 arguments/parameters.
    --Adjust code according to your need.
    --Its for C# Desktop application.
    --Visual Studio Professional, Framework (2.0)
    //Setting connections.
    OracleConnection con=new OracleConnection("Data Source=orcl9i; user id=scott; password=tiger");
    OracleComand cmd=new OracleCommand(con);
    cmd.Type=CommandType.StoredProcedure; //you are useing SP
    cmd.Text="my_stored_procedure"; //Mention SP name.
    --if DataRow has Three columns. You need three parameters.
    OracleParameter p1=new OracleParameter ();//By default parameters are input parameters.
    OracleParameter p2=new OracleParameter ();
    OracleParameter p3=new OracleParameter ();
    //We assume that Datarow already has data in it.
    p1.ParametersName="sp_var1 ";
    p1.OracleDbType=OracleDbType.Varchar;
    p1.Value=tablenameRow[1]; //Here DataRow object's Column1 is input.
    p2.ParametersName="sp_var2 ";
    p2.OracleDbType=OracleDbType.Varchar;
    p2.Value=tablenameRow[2]; //Here DataRow object's Column2 is input.
    p3.ParametersName="sp_var3 ";
    p3.OracleDbType=OracleDbType.Varchar;
    p3.Value=tablenameRow[3]; //Here DataRow object's Column3 is input.
    cmd.OracleParameter.Add(p1); //Add parameters.
    cmd.OracleParameter.Add(p2); //Add parameters.
    cmd.OracleParameter.Add(p3); //Add parameters.
    cmd.ExecuteNonQuery(); //Execute Procedure here.
    Feel free to ask if still found problem.
    ....

  • I can't pass empty string as column of Table Valued Parameter.

    Hello.
    I have stored procedure which accept TVP with columns of 'sql_variant' type. And I have C++ application which call this stored procedure.
    When i pass some non-empty string as sql_variant from my application - all works fine.
    But when I need to pass empty string ("") as sql_variant - I get following error:
    "OLEDB hr = 0x80040e14
     #0:  OLEDB provider error 3621  "The statement has been terminated."
     #1:  OLEDB provider error 8062  "The data for the table-valued parameter 1 doesn't conform to the table type of the parameter."
     #2:  OLEDB provider error 8046  "The incoming tabular data stream (TDS) remote procedure call (RPC) protocol stream is incorrect. Table-valued parameter 0 (""), row 1, column 1: The supplied length is not valid for data type sql_variant.
    Check the source data for invalid lengths. An example of an invalid length is data of nchar type with an odd length in bytes."  
    Could you please help me deal with that issue?
    Thanks,
    Vitaliy

    Dear Vitaliy,
    Thank you for your question.
    Based on my understanding of your question, the issue is related with passing SQL_VARIANT data type in C++ application using Microsoft OLE DB Provider.
    As we can see from http://msdn.microsoft.com/en-us/library/ms173829(v=sql.100).aspx:
    ODBC does not fully support sql_variant. Therefore, queries of sql_variant columns are returned as binary data when you use Microsoft OLE DB Provider for ODBC (MSDASQL). For example, a sql_variant column that contains the character string data 'PS2091'
    is returned as 0x505332303931.
    According to above statement, as you are using OLEDB provider for ODBC with sql_variant in your application, it is not fully support. Seems there are some conversion failure within the Stored Procedure calling. You may consider to adjust your application
    slightly to use other commonly supported data types which also fits your application requirements.
    I listed some more information regarding sql_variant below for your reference:
    A column of type sql_variant may contain rows of different data types such as int, binary and char values.
    A sql_variant data type must first be cast to its base data type value
    before participating in operations such as addition and subtraction. You can find the conversion details in "Comparings sql_variant Values" part.
    Below types of values cannot be stored by using sql_variant:
    varchar(max)
    varbinary(max)
    nvarchar(max)
    xml
    text
    ntext
    image
    timestamp
    sql_variant
    geography
    hierarchyid
    geometry
    User-defined types
    Hope it will be helpful.
    Thank you!
    Best Regards,
    SQL Team - MSFT

  • How to pass parameter from 1 stored procedure to another stored procedure inside crystal report

    Hi
    I have several stored procedure in my Crystal Report. I am wondering if it is possible for me to pass a parameter to one of the stored procedure and to use the result of that stored procedure E.g. CustomerCode. To another 2 stored procedure to generate the report dynamically?
    I have 3 stored procedure
    The 1st one is used to gather information and process the calculation
    another 2 stored procedure is used for generate the graph and both of them required to take 2 parameters. The 1st stored procedure will require 1 parameter (E.G. Reference Code) and will return a set of information including the data that could be use on the other 2 stored procedures.
    After I added these 2 stored procedure, it requires me to pass 3 parameters to the report. I would like to know if I could only pass the Reference Code for stored procedure 1 and use it to retrieve the information for the other 2 parameter?
    Thanks in advance
    Chi

    Hi Chi
    To pass parameter from 1 stored procedure to another stored procedure, you will have to create sub report. In your case you will have to create 2 sub reports for 2nd and 3rd stored procedure and link those sub reports with the main report using Reference Code field in order to pass the values.
    After creating the report when you will refresh the report, it will ask 4 parameters, one parameter for main report, one for the first subreport and two for second subreport to fetch the data correctly.
    Regards
    Poonam Thorat.

  • Problem in OUT Parameter in the stored procedure

    Hi,
    I have a problem in the OUT parameter of the stored procedure under the package. I encountered the error PLS-00306. Below are the codes.
    Package
    CREATE OR REPLACE package body test as
         procedure sp_countries(rst OUT country_typ) as
         sql_stmt VARCHAR2(300);
         begin
         sql_stmt := 'SELECT * FROM countries WHERE region_id = 1';
         OPEN rst FOR sql_stmt;     
         end;
    end test;
    by the way. i declared the country_typ as this:
    TYPE country_typ IS REF CURSOR;
    Here is the code that will call this package:
    declare
    tst countries%ROWTYPE;
    begin
    test.sp_countries(tst);
    dbms_output.put_line(tst.country_name);
    end;

    Works for me. Although I had to use emp instead of your table:
    SQL> create or replace
      2  package test as
      3     TYPE country_typ IS REF CURSOR;
      4     procedure sp_countries(rst OUT country_typ);
      5  end;
      6  /
    Package created.
    SQL> CREATE OR REPLACE
      2  package body test as
      3     procedure sp_countries(rst OUT country_typ) as
      4        sql_stmt VARCHAR2(300);
      5     begin
      6        sql_stmt := 'SELECT * FROM emp WHERE deptno = 20';
      7        OPEN rst FOR sql_stmt;
      8     end;
      9  end test;
    10  /
    Package body created.
    SQL> var tcur refcursor
    SQL> exec test.sp_countries(:tcur);
    PL/SQL procedure successfully completed.
    SQL> print tcur
         EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO
          7369 SMITH      CLERK           7902 17-DEC-80        800                    20
          7566 JONES      MANAGER         7839 02-APR-81       2975                    20
          7788 SCOTT      ANALYST         7566 19-APR-87       3000                    20
          7876 ADAMS      CLERK           7788 23-MAY-87       1100                    20
          7902 FORD       ANALYST         7566 03-DEC-81       3000                    20
    SQL>

  • Table of records from a stored procedure

    Hi
    Where could I find an example or documentation about how to retrive a table of records from a Stored Procedure ??
    Thanks

    Try:
    CREATE OR REPLACE TYPE scott.MYRECORDTYPE as object
    (a int, b varchar2(40), c date, d number(10));
    CREATE OR REPLACE TYPE scott.MYTABLETYPE is table of myrecordtype;
    CREATE OR REPLACE PACKAGE BODY scott.MYPACKAGE
    as
    type number_collection is table of number(38) index by binary_integer;
    type varchar2_collection is table of varchar2(4000) index by binary_integer;
    type date_collection is table of date index by binary_integer;
    g_data myTableType;
    empno_col number_collection;
    ename_col varchar2_collection;
    hiredate_col date_collection;
    mgr_col number_collection;
    function my_function return myTableType
    is
    begin
    select empno, ename, hiredate, mgr
    bulk collect into empno_col, ename_col, hiredate_col, mgr_col
    from emp
    order by empno; -- Get some data
    g_data := myTableType(); -- Initialize
    for i in empno_col.first .. empno_col.last loop
    g_data.extend; -- Write something in the array
    g_data(i) := myRecordtype(empno_col(i), ename_col(i), hiredate_col(i), mgr_col(i));
    end loop;
    return g_data;
    end;
    end;
    -- Demonstration-View
    CREATE OR REPLACE VIEW scott.myview
    AS
    select a,b,c,d
    from table(cast(myPackage.my_function() as mytabletype));

Maybe you are looking for