Table as parameter for function with table value from Exec query in SQL

I have a Query query that returns Error as "Must declare scalar variable" @tbl ".

declare   @tbl  as ItemName_Id_Table
                 ,@Entry_Date_To varchar(50) = '2017-10-22'
                 ,@qry nvarchar(max)
set @qry = 
    'SELECT        
            tblStockLedger.item_id, tblStockLedger.inward_qty, tblStockLedger.inward_qty2, Fn_StockValue_1.Value
    FROM    tblStockLedger 
        LEFT OUTER JOIN dbo.Fn_StockValue('''+@Entry_Date_To+''',@tbl) AS Fn_StockValue_1 
            ON tblStockLedger.item_id = Fn_StockValue_1.item_id
    GROUP BY 
            tblStockLedger.item_id, tblStockLedger.inward_qty, tblStockLedger.inward_qty2, Fn_StockValue_1.Value'
exec(@qry)

Can someone explain to me how to overcome this error.

+4
source share
1 answer

You need to use SP_EXECUTESQLit to pass the type of table to work inside a dynamic query. You can also parameterize a variable @Entry_Date_Toinstead of concatenating strings

DECLARE @tbl           AS ITEMNAME_ID_TABLE, 
        @Entry_Date_To date = '2017-10-22',  --changed to date
        @qry           NVARCHAR(max) 

SET @qry = 'SELECT tblStockLedger.item_id, 
                   tblStockLedger.inward_qty, 
                   tblStockLedger.inward_qty2, 
                   Fn_StockValue_1.Value             
            FROM tblStockLedger  
            LEFT OUTER JOIN dbo.Fn_StockValue(@Entry_Date_To,@tbl) AS Fn_StockValue_1                  
                         ON tblStockLedger.item_id = Fn_StockValue_1.item_id         
            GROUP BY tblStockLedger.item_id, 
                     tblStockLedger.inward_qty, 
                     tblStockLedger.inward_qty2, 
                     Fn_StockValue_1.Value'

EXEC Sp_executesql 
    @qry, 
    N'@tbl ItemName_Id_Table READONLY, @Entry_Date_To Date', 
    @tbl,@Entry_Date_To

Note. . You pass an empty table variable @tblfor the function

+2
source

Source: https://habr.com/ru/post/1682554/


All Articles