如何执行返回表的用户定义函数sql?

时间:2014-03-27 07:48:11

标签: sql sql-server

我正在使用SQL Server 2012。

我在sql中创建了一个函数,如下所示:

CREATE FUNCTION [dbo].[Fn_IsCompanyExistInUserLocation](@CompanyId int)

RETURNS @Result table
(
UserId int null
)
AS
BEGIN
    insert into @Result(UserId) select UL.UserId FROM [RRT_Reporting].[dbo].[UserLocation] as UL where UL.CompanyId=@CompanyId and UL.LocationType='COMPANY'


    RETURN 
END

我不确定是否正确。

现在我正在尝试执行此功能,如:

DECLARE @ret as table (UserId int null) 

EXEC @ret = [dbo].[Fn_IsCompanyExistInUserLocation] @CompanyId= 10; 

select UserId from @ret

我收到了错误:

Msg 137, Level 16, State 1, Line 6
Must declare the scalar variable "@ret".

2 个答案:

答案 0 :(得分:2)

试试这个:

DECLARE @ret table (UserId int null) 
insert into @ret select * from [dbo].[Fn_IsCompanyExistInUserLocation](10)
select UserID from @ret

答案 1 :(得分:0)

我明白了:

SELECT *
FROM [dbo].[Fn_IsCompanyExistInUserLocation](10)