我有这样的查询:
UPDATE RM
SET RM.WEEK_1 = (
SELECT P.AVERAGE_AVAI FROM dbo.f_SCAVAI_GetWeekAverage(RM.OPRO_KEY, @WEEKS_MONTH, @cWorkDaysOnly, RM.KAPACITETA) P WHERE P.WEEKOFMONTH = 1
),
RM.WEEK_2 = (
SELECT P.AVERAGE_AVAI FROM dbo.f_SCAVAI_GetWeekAverage(RM.OPRO_KEY, @WEEKS_MONTH, @cWorkDaysOnly, RM.KAPACITETA) P WHERE P.WEEKOFMONTH = 2
),
RM.WEEK_3 = (
SELECT P.AVERAGE_AVAI FROM dbo.f_SCAVAI_GetWeekAverage(RM.OPRO_KEY, @WEEKS_MONTH, @cWorkDaysOnly, RM.KAPACITETA) P WHERE P.WEEKOFMONTH = 3
),
RM.WEEK_4 = (
SELECT P.AVERAGE_AVAI FROM dbo.f_SCAVAI_GetWeekAverage(RM.OPRO_KEY, @WEEKS_MONTH, @cWorkDaysOnly, RM.KAPACITETA) P WHERE P.WEEKOFMONTH = 4
),
RM.WEEK_5 = (
SELECT P.AVERAGE_AVAI FROM dbo.f_SCAVAI_GetWeekAverage(RM.OPRO_KEY, @WEEKS_MONTH, @cWorkDaysOnly, RM.KAPACITETA) P WHERE P.WEEKOFMONTH = 5
),
RM.WEEK_6 = (
SELECT P.AVERAGE_AVAI FROM dbo.f_SCAVAI_GetWeekAverage(RM.OPRO_KEY, @WEEKS_MONTH, @cWorkDaysOnly, RM.KAPACITETA) P WHERE P.WEEKOFMONTH = 6
)
FROM @ROOMS_BY_DEPA_KEY1 RM
这样可行,但速度很慢,因为每周的号码都会调用dbo.f_SCAVAI_GetWeekAverage
。此函数返回给定OPRO_KEY
的相同结果。基本上,如果每行只调用一次此函数(OPRO_KEY
一次)就足够了,然后每周的结果将从该表更新。可以这样做吗?那么,不是每周都调用这个函数,而是每行调用一次,而且根据WEEKOFMONTH
更新几周?
答案 0 :(得分:1)
请尝试以下查询并检查效果
UPDATE RM
SET RM.WEEK_1 = (CASE WHEN WA.WEEKOFMONTH = 1 THEN WA.AVERAGE_AVAI ELSE RM.WEEK_1 END)
,RM.WEEK_2 = (CASE WHEN WA.WEEKOFMONTH = 2 THEN WA.AVERAGE_AVAI ELSE RM.WEEK_2 END)
,RM.WEEK_3 = (CASE WHEN WA.WEEKOFMONTH = 3 THEN WA.AVERAGE_AVAI ELSE RM.WEEK_3 END)
,RM.WEEK_4 = (CASE WHEN WA.WEEKOFMONTH = 4 THEN WA.AVERAGE_AVAI ELSE RM.WEEK_4 END)
,RM.WEEK_5 = (CASE WHEN WA.WEEKOFMONTH = 5 THEN WA.AVERAGE_AVAI ELSE RM.WEEK_5 END)
,RM.WEEK_6 = (CASE WHEN WA.WEEKOFMONTH = 6 THEN WA.AVERAGE_AVAI ELSE RM.WEEK_6 END)
FROM @ROOMS_BY_DEPA_KEY1 RM
OUTER APPLY(
SELECT P.AVERAGE_AVAI,P.WEEKOFMONTH
FROM dbo.f_SCAVAI_GetWeekAverage(RM.OPRO_KEY, @WEEKS_MONTH, @cWorkDaysOnly, RM.KAPACITETA) P
) AS WA