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

时间:2014-06-26 17:18:43

标签: sql-server tsql 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
    )

我现在需要UDF返回@Financials。

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

1 个答案:

答案 0 :(得分:4)

返回表变量时,您不会使用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