SQL Server 2008表变量错误:必须声明标量变量“@RESULT”

时间:2010-03-23 00:23:21

标签: sql sql-server sql-server-2008

我第一次使用表值作为SQL Server 2008中函数的参数。下面的代码会产生此错误:

必须声明标量变量“@RESULT”。

为什么?我在函数的第一行声明它了!

        ALTER FUNCTION f_Get_Total_Amount_Due(

      @CUSTOMER_LIST   [tpCSFM_CUSTOMER_SET_FOR_MONEY] READONLY

    )
    RETURNS [tpCSFM_CUSTOMER_SET_FOR_MONEY]
    AS
    BEGIN


 --Prepare the return value, start with initial customer list
 DECLARE @RESULT AS [tpCSFM_CUSTOMER_SET_FOR_MONEY]
 INSERT INTO @RESULT SELECT * FROM @CUSTOMER_LIST

 --Todo: populate with real values
 UPDATE @RESULT SET tpCSAM_MONEY_VALUE = 100

 --return total amounts as currency
 RETURN @RESULT

 END

3 个答案:

答案 0 :(得分:3)

您的声明将属于'多语句表值函数'案例:

Multistatement Table-valued Functions
CREATE FUNCTION [ schema_name. ] function_name 
( [ { @parameter_name [ AS ] [ type_schema_name. ] parameter_data_type 
    [ = default ] [READONLY] } 
    [ ,...n ]
  ]
)
RETURNS @return_variable TABLE <table_type_definition>
    [ WITH <function_option> [ ,...n ] ]
    [ AS ]
    BEGIN 
                function_body 
        RETURN
    END
[ ; ]

不幸的是@return_variable不能声明为表类型,你必须将TVP类型的声明复制到函数返回表类型中。

答案 1 :(得分:2)

这个编译很好:

--Returns the name of the field to use to find results
ALTER FUNCTION f_Get_Total_Amount_Due(
    @CUSTOMER_LIST          [tpCSFM_CUSTOMER_SET_FOR_MONEY] READONLY
)
RETURNS @RESULT TABLE(
    tpCSFM_CUS_ID   uniqueidentifier PRIMARY KEY,
    tpCSFM_MONEY_VALUE  MONEY NULL
)
AS
BEGIN
--Prepare the return value, start with initial customer list
INSERT INTO @RESULT SELECT * FROM @CUSTOMER_LIST

--Todo: populate with real values
UPDATE @RESULT SET tpCSFM_MONEY_VALUE = 100

--return total amounts as currency
RETURN
END

答案 2 :(得分:0)

I don't believe the table-valued functions got any new features表示返回值可以是用户定义的表类型。

但是,您可以尝试:RETURNS @RESULT [tpCSFM_CUSTOMER_SET_FOR_MONEY]并删除您单独的DECLARE。

当我有机会设置测试用例时,我需要查看它。