我有一个曾经工作的表值函数,但不再存在或者至少花费很多时间。
唯一可能改变的是查询读取的表上的数据量。
这是该功能的代码。
ALTER FUNCTION [dbo].[SUPERVISOR_NOMINA2] (@iniDATE DATE,@endDATE DATE)
RETURNS @TABLA TABLE (
[ID] INT NOT NULL PRIMARY KEY CLUSTERED
,[EFEC] FLOAT NOT NULL
,[TOP] FLOAT NOT NULL
,[EXTRA] FLOAT NOT NULL
,[DEUDA] FLOAT NOT NULL
)
AS
BEGIN
INSERT INTO @tempTABLE
/*------RUN FROM HERE TO TEST-------
DECLARE @iniDATE DATE,@endDATE DATE
SET @iniDATE = '2013-02-20'
--*/
SELECT
SOURCE.[ID],SOURCE.[NAME],SOURCE.[CAMPAIGN],[SUPERVISOR],[FLOOR MANAGER],[LAST LOGON],[EFEC],[TOP]
,[HR+] AS EXTRA
,CASE
WHEN [DIF] >= 0 THEN 0
ELSE [DIF]
END AS DEUDA
FROM (
SELECT
NM.[ID]
,NM.[NAME]
,NM.[CAMPAIGN]
,NM.[SUPERVISOR]
,SUM(CASE
WHEN [ATT ID] > 4 AND [ATT ID] <> 7 THEN '0'
ELSE ROUND([EFEC],2)
END) AS [EFEC]
,SUM(CASE
WHEN [ATT ID] > 4 AND [ATT ID] <> 7 THEN '0'
ELSE [TOP]
END) AS [TOP]
,SUM(CASE
WHEN [ATT ID] > 4 AND [ATT ID] <> 7 THEN '0'
WHEN [EFEC] < [TOP] THEN 0
WHEN [TOP]+[EXHR] > [EFEC] THEN ROUND([EFEC]-([TOP]+[EXHR]),0,1)
ELSE [EXHR]
END) AS [HR+]
,ROUND(SUM(CASE
WHEN [ATT ID] > 4 AND [ATT ID] <> 7 THEN '0'
WHEN [EFEC] < [TOP] THEN ROUND([EFEC]-[TOP],2)
WHEN [TOP]+[EXHR] > [EFEC] THEN ROUND([EFEC]-([TOP]+ROUND([EFEC]-([TOP]+[EXHR]),0,1)),2)
ELSE ROUND([EFEC]-([TOP]+[EXHR]),2)
END),2) AS [DIF]
FROM [WFO].[dbo].[VIEW_NOMINA] NM
FULL JOIN [WFO].[dbo].[VIEW_ATTENDANCE] AT ON NM.ID = AT.ID AND NM.DATE = AT.DATE
WHERE NM.DATE < CONVERT(DATE,GETDATE()) AND NM.[DATE] BETWEEN @iniDATE AND @endDATE
GROUP BY NM.[ID],NM.[NAME],NM.[CAMPAIGN],NM.[SUPERVISOR]) SOURCE
LEFT JOIN (
SELECT [ID],CONVERT(DATE,MAX(DATETIME)) AS [LAST LOGON]
FROM [WFO].[dbo].[AGENT-LOGBOOK]
GROUP BY [ID]
) LT ON LT.ID = SOURCE.ID
LEFT JOIN [WFO].[dbo].[SUPERVISORS] SP ON SP.NAME = SOURCE.SUPERVISOR
ORDER BY [NAME]
RETURN
END
有趣的是,如果我只是在insert语句之后和return语句之前运行查询,那么查询将在几秒钟内完成。
你有什么建议我做错了?
答案 0 :(得分:0)
一个可能的问题是你的where子句中的这个SQL:
NM.DATE < CONVERT(DATE,GETDATE())
除了在这种情况下我非常确定CONVERT
是不必要的这一事实之外,以这种方式使用函数通常可以使得你所使用的索引不会被使用。
答案 1 :(得分:0)
这甚至可以运行吗?许多CASE语句为一个案例返回一个字符,为另一个案例返回一个数字。这应该失败。改变所有这样的行
WHEN [ATT ID] > 4 AND [ATT ID] <> 7 THEN '0'
到这个
WHEN [ATT ID] > 4 AND [ATT ID] <> 7 THEN 0