我正在将现有函数从Scalar转换为Table-Valued,这是标量函数:
ALTER FUNCTION [dbo].[fn_TotalClient]
(
@ClinicId AS int,
@FromDate AS DateTime,
@ToDate AS DateTime
)
RETURNS int
AS
BEGIN
DECLARE @result int;
set @result = (Select TOP 1 Count(*) as TotalClient
FROM (SELECT dbo.Clinic.ClinicId, Count(*) as TotalVisit
FROM dbo.Clinic INNER JOIN
dbo.Visit ON dbo.Clinic.ClinicId = dbo.Visit.ClinicId
Where dbo.Visit.Date >= @FromDate AND dbo.Visit.Date <= @toDate AND dbo.Visit.ClinicId = @ClinicId
Group By dbo.Clinic.ClinicId, dbo.Visit.ClientId) as v
Group By v.ClinicId
);
RETURN @result;
END
这是我的尝试表值:
CREATE FUNCTION [dbo].[TotalClient](
@ClinicId AS int,
@FromDate AS DateTime,
@ToDate AS DateTime
)
RETURNS TABLE
AS
RETURN
Select TOP 1 Count(*) as TotalClient
FROM (
SELECT Count(*) as TotalVisit
FROM dbo.Clinic INNER JOIN
dbo.Visit ON dbo.Clinic.ClinicId = dbo.Visit.ClinicId
WHERE dbo.Visit.Date >= @FromDate AND dbo.Visit.Date <= @toDate AND dbo.Visit.ClinicId = @ClinicId
Group By dbo.Clinic.ClinicId, dbo.Visit.ClientId) as v
Group By v.ClinicId)
RETURNS int
我收到此错误:
Msg 102, Level 15, State 1, Procedure TotalClient, Line 24 Incorrect syntax near ')'.
我没有这方面的经验,非常感谢您的建议。
答案 0 :(得分:0)
删除最后一个)
以及最后一个RETURNS int
行。
即你的新SQL应该是这样的。
CREATE FUNCTION [dbo].[TotalClient](
@ClinicId AS int,
@FromDate AS DateTime,
@ToDate AS DateTime
) RETURNS TABLE
AS
RETURN
SELECT TOP 1 Count(*) as TotalClient
FROM ( SELECT Clinic.ClinicId, Count(*) as TotalVisit
FROM dbo.Clinic INNER JOIN
dbo.Visit ON dbo.Clinic.ClinicId = dbo.Visit.ClinicId
WHERE dbo.Visit.Date >= @FromDate AND dbo.Visit.Date <= @toDate
AND dbo.Visit.ClinicId = @ClinicId
GROUP BY dbo.Clinic.ClinicId, dbo.Visit.ClientId
) AS v
GROUP BY v.ClinicId