gpt4 book ai didi

sql - 表作为 SQL 中 Exec 查询的表值函数的参数

转载 作者:行者123 更新时间:2023-12-01 19:22:17 25 4
gpt4 key购买 nike

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

谁能解释一下如何克服这个错误。

最佳答案

您需要使用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表变量传递给函数

关于sql - 表作为 SQL 中 Exec 查询的表值函数的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45386161/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com