尝试编译函数的语法不正确

时间:2013-12-09 14:32:10

标签: sql-server-2005 user-defined-functions

我正在尝试创建以下功能:

CREATE FUNCTION fn_WarrantyTrend
returns @myTable table
(
    Years int 
)
AS
BEGIN
    insert into @myTable
    SELECT distinct YEAR(CurDate) from EOD_Main ORDER BY YEAR(CurDate) ASC
    RETURN 
END

我收到了这些错误:

  

Msg 102,Level 15,State 1,Procedure fn_WarrantyTrend,Line 2   
'return'附近的语法不正确。   
消息1087,第15级,状态2,程序fn_WarrantyTrend,第8行   
必须声明表变量“@myTable”。

1 个答案:

答案 0 :(得分:0)

如果从您编写的语法中收到错误,则应consult the documentation

CREATE FUNCTION dbo.fn_WarrantyTrend -- always use schema prefix
(
    @Years int -- need @variable syntax here
)
-- parameter list comes *before* RETURNS
RETURNS TABLE -- you should use an inline table-valued function when possible
AS
  RETURN 
  (
    SELECT DISTINCT CurDate = YEAR(CurDate) -- should alias the output column
      FROM dbo.EOD_Main -- again, always use SCHEMA prefix
      --ORDER BY YEAR(CurDate) ASC -- not possible to ORDER BY here without TOP
          -- the outer query that calls the function should apply any ORDER BY
  );

但有趣的是,您使用此@Years参数,并且从不使用它...

您还应该考虑创建函数WITH SCHEMABINDING。并here is background on always using the schema prefix

相关问题