有没有办法简化这个脚本,使 CASE 语句不重复?在这个缩短的示例中看起来可以接受,但实际上 CASE 语句要长得多,因为我有“每 2 周”、“每 4 周”、“每月”等案例。我使用 SQL Server 和 WHILE 语句来提高性能原因。CTE 或 MERGE 有帮助吗?
DECLARE @theStartDate DATE
DECLARE @Interval INT
DECLARE @eventCharges TABLE
(
[EventDate] [datetime],
Person_Id int
)
SET @today = GETDATE()
SET @Interval = 0
-- delete event charges from previous user
DELETE FROM @eventCharges
-- Insert the calculated transactions
WHILE @Interval < 100
BEGIN
SET @Interval = @Interval + 1
INSERT INTO @eventCharges
SELECT
CASE
WHEN pcc.Recurrence = 'Daily'
THEN DATEADD(DAY, @Interval, @theStartDate)
WHEN pcc.Recurrence = 'Weekly'
THEN DATEADD(WEEK, @Interval, @theStartDate)
END AS EventDate
,pcc.Person_Id
FROM @personChargeCurrent pcc
WHERE CASE
WHEN pcc.Recurrence = 'Daily'
THEN DATEADD(DAY, @Interval, @theStartDate)
WHEN pcc.Recurrence = 'Weekly'
THEN DATEADD(WEEK, @Interval, @theStartDate)
END <= @today
AND NOT EXISTS(SELECT 1 FROM dbo.PersonChargeTransaction pct
WHERE pct.Person_Id = pcc.Person_Id
AND pct.PersonCharge_Id = pcc.Id
AND pct.TransactionDate =
CASE
WHEN pcc.Recurrence = 'Daily'
THEN DATEADD(DAY, @Interval, @theStartDate)
WHEN pcc.Recurrence = 'Weekly'
THEN DATEADD(WEEK, @Interval, @theStartDate)
END)
ORDER BY StartDate
END