Sql server 如何在SQLServer中将UNIONALL包含查询作为标量函数
我试图创建一个标量函数,其中包含所有3个查询的ui,但我无法创建这里是我的查询Sql server 如何在SQLServer中将UNIONALL包含查询作为标量函数,sql-server,stored-procedures,sql-server-2012,Sql Server,Stored Procedures,Sql Server 2012,我试图创建一个标量函数,其中包含所有3个查询的ui,但我无法创建这里是我的查询 USE [dbname] GO /****** Object: UserDefinedFunction [dbo].[userinfo_getcountofemplyoee1] Script Date: 3/23/2017 11:51:22 AM ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO create FUNCTION [dbo].[us
USE [dbname]
GO
/****** Object: UserDefinedFunction [dbo].[userinfo_getcountofemplyoee1] Script Date: 3/23/2017 11:51:22 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create FUNCTION [dbo].[userinfo_gettotalcountofemplyoee](@parm Nvarchar(50)) RETURNS INTEGER
AS
BEGIN
DECLARE @id INTEGER,@child nvarchar
;with cte as
(
select userid, reportTo
from userinfo a
where not exists (select * from userinfo b where b.reportTo = a.userid)
union all
select ui.userid, ui.reportTo
from userinfo ui join cte on cte.reportTo = ui.userid
where ui.reportTo is not null
union all
select cte.userid, ui.reportTo
from userinfo ui join cte on cte.reportTo = ui.userid
where cte.reportTo is not null
)
, managers as (
select x.reportTo, count(*) TotalempUnderUser
from (select distinct userid, reportTo
from cte
where reportTo is not null) x
group by x.reportTo)
select managers.TotalempUnderUser
from managers where managers.reportTo=627
union all
select 0
from userinfo ui left join managers on ui.userid = managers.reportTo
where managers.reportTo is null and userid=627
select @id=TotalempUnderUser from cte
return @id
END
但我得到了错误
Msg 444,第16级,状态2,程序userinfo_GetCountOfEmployee1,第9行
函数中包含的Select语句无法向客户端返回数据
我已经更新了答案,请现在检查
我的样本数据是
userid FLname ReportTo TotalempUnderUser
1 abc null 4
2 xyz 1 2
3 aaa 1 0
4 wer 2 1
预期产量为
TotalempUnderUser
4
您可以这样做:
Declare @n int
;with cte as
(
Your query here that returns TotalempUnderUser
)
select @n=column_name from cte
return @n
或者看起来像你的
Declare @id integer
;with cte as
(
Your query here that returns TotalempUnderUser
)
select @id=column_name from cte
return @id
你的cte返回了多少条记录?只有一条记录TotalempUnderUserok等等……你明白我的意思了吗。。我只是简短地给出它,让您尽快理解。好的,我将尝试帮助您构建查询逐个构建查询。您能在此处提供示例数据和预期结果吗?请稍等