Search code examples
sqlsql-servertable-valued-parameterstable-variable

Not able to access Table Valued Parameter for queries in sql


I have two queries in the single stored procedure. I have one table table valued parameter & that TVP I am using for both the queries. One of my query is working fine (Update Query is working fine) but If I am using that same TVP for the insert query then it is not inserting the values to it. I dont know what is happening & also error is also not coming.

Here's my query :

CREATE TYPE Mapping_n_Info_Master_Type AS TABLE
(
    quantity INT,
    product_id INT,
    sell_order_no VARCHAR(20),
    selling_product_id VARCHAR(20),
    tax_id INT
);
GO

CREATE PROC spInsert_Rs_Sell_Order_Master
(
    @tvp_Mapping_n_Info_Master Mapping_n_Info_Master_Type READONLY
)
AS
BEGIN

    SET NOCOUNT ON
    BEGIN TRY
    BEGIN TRANSACTION

        --Start This Part is not Working
         INSERT INTO
            RS_Sells_Invoice_Info_Master 
         SELECT 
            sell_order_no,product_id,selling_product_id,tax_id,qty
         FROM
            @tvp_Mapping_n_Info_Master

        --End This Part is not Working


        --Insert Logic For Sell Order Mapping
        UPDATE 
            RS_Sell_Order_Mapping 
        SET
            quantity  = TVP.quantity    
        FROM 
            @tvp_Mapping_n_Info_Master tvp
            INNER JOIN RS_Sell_Order_Mapping AS SOM ON
            TVP.product_id = SOM.product_id AND TVP.sell_order_no = SOM.sell_order_no
        WHERE 
            SOM.product_id = TVP.product_id
                AND
            SOM.sell_order_no = TVP.sell_order_no

    COMMIT TRANSACTION

    END TRY

    BEGIN CATCH

         DECLARE @ERROR_MSG NVARCHAR(MAX), @SEVERITY INT, @STATE INT
         SELECT @SEVERITY = ERROR_SEVERITY(), @STATE = ERROR_STATE()
         ,@ERROR_MSG = ERROR_MESSAGE() + ' err src line: ' + CAST( ERROR_LINE() AS NVARCHAR(20)) + ' ' + ISNULL(ERROR_PROCEDURE(), '');           
         --@ERROR_MSG = ERROR_MESSAGE()
         ROLLBACK;
         -- RE-THROW EXCEPTION FOR DIAGNOSTIC VISIBILITY
         RAISERROR (@ERROR_MSG ,@SEVERITY, @STATE);         
         RETURN

    END CATCH
END

My Table looks like this enter image description here

Do I want to change the sequence of parameter that I have supplied to the insert query. Please give your suggestions to this


Solution

  • Write as:

    INSERT INTO 
    RS_Sells_Invoice_Info_Master (sell_order_no,
                                  product_id,
                                  selling_product_id,
                                  tax_id,
                                  qty) 
    SELECT MIM.sell_order_no,
           MIM.product_id,
           MIM.selling_product_id,
           MIM.tax_id,
           MIM.quantity
    FROM
    @tvp_Mapping_n_Info_Master as MIM;