简体   繁体   中英

Table as Parameter to Table-Valued Function from Exec Query in SQL

I have following Query which returns Error like 'Must declare the 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)

Could any one please explain me how to overcome this Error.

You need it use SP_EXECUTESQL to pass the table type to function inside dynamic query. You can also parameterize @Entry_Date_To variable instead of string concatenation

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 are passing empty @tbl table variable to function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM