2

我有一个 SQL 函数,我想返回一个表,但我收到一个错误: A RETURN statement with a return value cannot be used in this context.

这是我的查询:

 ALTER FUNCTION [dbo].[Fnc_GetParentCategories]-- 21
  ( 
@catId int
  )
   Returns table

As
 Begin

Declare @Table table(Id int identity(1,1),Category_Id int,ParentId int);
declare @cid int;
 WITH  x AS (              
 SELECT a.Category_Id, a.ParentId               
 FROM   t_Category a              
 WHERE a.Category_Id=@CatId -- enter dead node walking here              

 UNION  ALL              
 SELECT b.Category_Id, b.ParentId              
 FROM   t_Category b              
 JOIN x   ON x.Category_Id  =b.ParentId            
  )             

  insert into @Table select * from x;

 return @Table 

end

错误是:

在此上下文中不能使用具有返回值的 RETURN 语句

4

2 回答 2

1

--Transact-SQL 多语句表值函数语法

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
[ ; ]

您修改后的功能

ALTER FUNCTION [dbo].[Fnc_GetParentCategories]-- 21
 ( 
  @catId int
  )
RETURNS @Table TABLE(Id int identity(1,1),Category_Id int,ParentId int)
As
BEGIN
WITH x AS
 (              
  SELECT a.Category_Id, a.ParentId               
  FROM t_Category a              
  WHERE a.Category_Id = @CatId -- enter dead node walking here                  
  UNION ALL              
  SELECT b.Category_Id, b.ParentId              
  FROM t_Category b              
  JOIN x ON x.Category_Id = b.ParentId            
  )             
  INSERT @Table select * from x;
  RETURN
END
于 2013-06-18T08:00:40.813 回答
1

您的查询不正确:

ALTER FUNCTION [dbo].[Fnc_GetParentCategories]-- 21
(
    @catId int
)
Returns @Table table
(
    Id int identity(1,1),
    Category_Id int,
    ParentId int
)
AS
    Begin

    WITH  x AS
    (
         SELECT a.Category_Id, a.ParentId
         FROM   t_Category a
         WHERE a.Category_Id=@CatId -- enter dead node walking here

         UNION  ALL

         SELECT b.Category_Id, b.ParentId
         FROM   t_Category b
         JOIN x   ON x.Category_Id  =b.ParentId
    )

    insert into @Table select * from x;

    return

end

你在之前声明你的表定义as

于 2013-06-18T08:01:12.207 回答