2013-06-18 39 views
2

我有一個SQL函數,我想返回一個表格,但出現錯誤: A RETURN statement with a return value cannot be used in this context如何在sql函數中返回表格

這裏是我的查詢:

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 [email protected] -- 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 

和錯誤是:

A RETURN statement with a return value cannot be used in this context

+2

你能後,你得到的錯誤之前?它將幫助我們更快地識別問題。 –

+0

帶有返回值的RETURN語句不能在此上下文中使用。 – Cronaldo

回答

0

--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 
+0

不能在'dbo.Fnc_GetParentCategories'上執行更改,因爲它是不兼容的對象類型。 – Cronaldo

+0

@Anilkumar M我怕你錯了。再試一次 –

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 [email protected] -- 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