gpt4 book ai didi

sql-server - 如何从函数(UDF)返回表变量?

转载 作者:行者123 更新时间:2023-12-04 00:36:04 25 4
gpt4 key购买 nike

我正在使用 SQL Server 2012,我一直在尝试许多不同的方法来从函数内部返回一个表变量,但我无法让它工作。我试过将变量声明移动到不同的地方等。这是 sql 的内容。如果可以的话,请将内容包装在一个 UDF 函数中,该函数实际编译并返回 @Financials 表变量,我将不胜感激。 sql 运行良好,没有问题。但是当我尝试将它包装在 UDF 中时,它会在我尝试创建它时抛出错误。我对一些内容进行了硬编码,以使其更易于测试和可视化。

DECLARE @Financials TABLE (
[a bunch of variable declarations in here]
);

insert into @Financials
[big old SELECT query here - this all works fine, and populates @Financials]

select *
from @Financials f1
where f1.TransactionDate = (
select MAX(TransactionDate)
from @Financials
where SalesDocumentItemID = f1.SalesDocumentItemID
)

我现在需要 UDF 返回@Financials。

如果这不可能,请考虑我的实际问题,如上面的 select * from @Financials 所示,我只想匹配由 SalesDocumentItemID 加入的最新 TransactionDate。如果我能找到一种有效的方法来执行此操作,那么我根本不需要将 INSERT 插入到@Financials 中。我想问题是填充@Financials 的查询很复杂,有很多连接,我不想在子选择中再次复制所有这些。但我猜想有一种很棒且更简单的方法可以做到这一点。会喜欢一些想法。

最佳答案

当返回一个表变量时,你不使用DECLARE。在 RETURNS 子句中定义结果表。

CREATE Function GetFinancials ()
RETURNS @financials TABLE
(
[a bunch of variable declarations in here]
)
AS
BEGIN
insert into @Financials
[big old SELECT query here - this all works fine, and populates @Financials]

RETURN
END

更新

如何在存储过程中返回最终结果?

create procedure uspGetFinanicals
as
declare @financial table
(
[table definition here]
)

insert into @financial
select dbo.GetFinancials()

select *
from @Financials f1
where f1.TransactionDate = (
select MAX(TransactionDate)
from @Financials
where SalesDocumentItemID = f1.SalesDocumentItemID
)

更新

试试这个。在 UDF 中创建一个表变量来存储第一次 select 的结果,然后将最终查询的结果插入到返回值中。

CREATE Function GetFinancials ()
RETURNS @financials TABLE
(
[a bunch of variable declarations in here]
)
AS
BEGIN
declare @table table([a bunch of variable declarations in here])
insert into @table
[big old SELECT query here - this all works fine, and populates @Financials]

insert into @Financials
select *
from @table f1
where f1.TransactionDate = (
select MAX(TransactionDate)
from @table
where SalesDocumentItemID = f1.SalesDocumentItemID
)

RETURN
END

关于sql-server - 如何从函数(UDF)返回表变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24436609/

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