我有一个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语句不能在此上下文中使用
答案 0 :(得分: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
答案 1 :(得分: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