CREATE FUNCTION dbo.GetPD
(
@ReportDate datetime,
@ItemId int
)
RETURNS int
AS
BEGIN
RETURN ISNULL((
SELECT TOP 1
PD * 2
FROM TMP_PDIndicatorsHistory
WHERE
ItemId = @ItemId
AND ReportDate < @ReportDate
ORDER BY RecId DESC
),0)
END;
DECLARE @DateFrom date = '2025-06-06'
;with cte as (
SELECT TOP 100 PERCENT
rih.recId,
@DateFrom AS ReportDate,
GetPD(rih.ScheduleId, rih.ReportDate, rih.CompanyId) AS PD
FROM PDIndicatorsHistory rih
WHERE
rih.ItemId= 111407
and rih.reportdate = @DateFrom
ORDER BY reportdate, RecId
UNION ALL
SELECT TOP 100 PERCENT
rih.recId,
rih.ReportDate,
GetPD(rih.ScheduleId, rih.ReportDate, rih.CompanyId) AS PD
FROM PDIndicatorsHistory rih
JOIN cte ON rih.ReportDate = DATEADD(DAY, 1, cte.ReportDate)
WHERE
rih.ItemId= 111407
AND rih.ReportDate <= GETDATE()
ORDER BY reportdate, RecId
)
UPDATE rih
SET
PD = cte.pd
FROM PDIndicatorsHistory rih
JOIN cte on cte.recid = rih.recid
Спасибо за помощь