Her*_*der 3 t-sql sql-server sql-server-2012
我正在使用 SQL Server 2012 并且我一直在尝试许多不同的方法来从函数内部返回表变量,但我无法让它工作。我试过将变量声明移动到不同的地方,等等。这里是 sql 的内容。如果您可以将胆量包装在实际编译并返回 @Financials 表变量的 UDF 函数中,我将不胜感激。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
)
Run Code Online (Sandbox Code Playgroud)
我现在需要 UDF 返回 @Financials。
如果这是不可能的,请考虑我的真正问题,它显示在上面的 select * from @Financials 中,我只想匹配最新的 TransactionDate,由 SalesDocumentItemID 加入。如果我能找到一种有效的方法来做到这一点,我根本不需要对 @Financials 执行 INSERT。我想问题是填充@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
Run Code Online (Sandbox Code Playgroud)
如何在存储过程中返回最终结果?
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
)
Run Code Online (Sandbox Code Playgroud)
尝试这个。在 UDF 中创建一个表变量来存储第一次选择的结果,然后将最终查询的结果插入到返回值中。
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
Run Code Online (Sandbox Code Playgroud)