2017-07-29 84 views
4

我有以下查詢返回錯誤,如'必須聲明標量變量'@tbl''。表作爲參數從SQL執行查詢表值函數

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('''[email protected]_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) 

請問任何人請解釋我如何克服這個錯誤。

回答

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表變量起作用

+0

在那裏我有越來越像「的表值參數錯誤‘@tbl’絕用READONLY選項聲明「。 – jamshi

+0

它的作品,但是,我試圖通過只有一個身份證但在那裏顯示完整的ID細節。 – jamshi

+1

@jamshi - 嘗試將'Left join'改爲'Inner join' –