表作为SQL中的Exec Query的表值函数的参数

时间:2017-07-29 06:34:32

标签: sql sql-server tsql sql-server-2012

我有以下Query,它返回错误,如'必须声明标量变量'@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)

任何人都可以解释一下如何克服这个错误。

1 个答案:

答案 0 :(得分:2)

您需要使用SP_EXECUTESQL将表类型传递给动态查询中的函数。您还可以参数化@Entry_Date_To变量而不是字符串连接

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

注意:您正在将空@tbl表变量传递给函数