我继承了一个用户定义的函数,我正在尝试修改并且遇到了一些问题。我想将其修改为常规查询,然后将其变为视图。该函数是 ufn_B2H_Enrolled_Clients_List。 此功能拉取在选定时间段内注册程序的客户列表。在 ufn_B2H_Enrolled_Clients_List中有一个函数ufn_B2H_STATUSES_THROUGH_DT。这会选择客户在所选时间范围内的最大状态更改,因此如果客户注册然后取消注册然后再次注册,则该功能不会将它们纳入计数。
我想要的是采用 ufn_B2H_Enrolled_Clients_List 并将其转换为常规查询/视图,输出如下所示:
Total_Clients_Enrolled Month Year
252 1 2013
247 2 2013
303 3 2013
**ufn_B2H_Enrolled_Clients_List Function**
RETURNS varchar(100)
AS
BEGIN
-- Declare the return variable here
DECLARE @VALUE varchar(100)
SELECT @VALUE = VALUE
FROM ENUMS
WHERE NAME = @NAME AND NUMBER = @NUMBER
IF @VALUE IS NULL
SET @VALUE = 'unknown'
RETURN (@VALUE)
END
GO
CREATE FUNCTION [dbo].[ufn_B2H_Enrolled_Clients_List](@From_DT datetime, @To_DT datetime)
RETURNS @retB2H_Enrolled_Clients_List TABLE
(
CLT_NBR int
)
AS
BEGIN
INSERT INTO @retB2H_Enrolled_Clients_List
--Include all clients enrolled prior to the period end date
SELECT CLT_NBR
FROM ECMS.dbo.ufn_B2H_STATUSES_THROUGH_DT(@To_DT) s1
WHERE s1.B2H_STATUS=4 AND s1.Max_Effect_DT <DATEADD(d,1,@To_DT)
--Exclude all clients disenrolled or transferred out prior to the start date
EXCEPT
SELECT s2.CLT_NBR
FROM ECMS.dbo.ufn_B2H_STATUSES_THROUGH_DT(@To_DT) s2 JOIN ECMS.dbo.ufn_B2H_STATUSES_THROUGH_DT(@To_DT) s1 ON s1.CLT_NBR=s2.CLT_NBR
WHERE s2.B2H_STATUS IN (7,9) AND s2.Max_Effect_DT <@From_DT AND s2.Max_Effect_DT>s1.Max_Effect_DT AND s1.B2H_STATUS IN (4,8)
--Exclude all clients who transferred in after the prior end date.
EXCEPT
SELECT s3.CLT_NBR
FROM ECMS.dbo.B2H_STATUS s3 JOIN ECMS.dbo.ufn_B2H_STATUSES_THROUGH_DT(@To_DT) s1 ON s1.CLT_NBR=s3.CLT_NBR
WHERE s3.B2H_STATUS = 8 AND s1.B2H_STATUS IN (4,8) AND s3.EFFECT_DT > @To_DT AND s3.Effect_DT>s1.Max_Effect_DT
RETURN
END
GO
CREATE FUNCTION [dbo].[ufn_B2H_STATUSES_THROUGH_DT](@Through_DT datetime)
RETURNS @retB2H_STATUSES_THROUGH_DT TABLE
(
CLT_NBR int
,B2H_STATUS int
,Max_EFFECT_DT datetime
)
AS
BEGIN
INSERT INTO @retB2H_STATUSES_THROUGH_DT
S
ELECT CLT_NBR
,B2H_STATUS
,MAX(EFFECT_DT) AS Max_Effect_DT
FROM [ECMS].[dbo].[B2H_STATUS]
WHERE EFFECT_DT<DATEADD(d,1,@Through_DT)
GROUP BY CLT_NBR, B2H_STATUS
RETURN
END
GO