2013-02-08 224 views
0

我有這個問題:客戶名單與他們的下一個計劃,重複的約會,即每年,每月或每季度。計算日期

的表\我的欄目有:

customer 
    customer_ID 
service 
    customer_ID 
    service_RecID 
Resource 
    service_RecID 
    Recurrence_RecID 
    Date_Time_Start 
Recurrence 
    Recurrence_RecID 
    RecurType 
    RecurInterval 
    DaysOfWeek 
    AbsDayNbr 
    SelectInterval 

它做成這樣,當賽程設置中,DATE_START_TIME是當第一次任命再次發生發生的日期。防爆。

Recurrence_RecID = 10 
RecurType = m (could be y, or d as well for yearly or daily) 
RecurInterval = 6 (if recurType = y, this would mean every 6 years) 

鑑於該系統生成這些夜間,我將如何編寫一個查詢來計算下一調度的約會,爲每一個客戶?我最初想到使用Resource.Date_Time_Start並循環直到變量nextAppointment> = today(),但是在SQL中運行循環是否是一種好的做法?

如果需要更多信息,請告訴我。非常感謝!

編輯:我會做一個sqlfiddle。

+2

你可以做一個sqlfiddle? – Raptor

+0

因此,RecurType中的'd'意味着'季度'? –

+0

您可以通過記錄上次用戶預約約會的日期,讓您的生活變得更加輕鬆,因此您只需要處理添加一次間隔的重複。您可能需要資源表中的第二列以記錄第一次和最近的約會。 –

回答

1

我會建議使用子查詢而不是循環。更高效的方式。這可能不準確,但類似...

SELECT 
    * 
FROM 
(  
SELECT 
    customer.customer_id, 
    service.service_RecID, 
    Resource.Date_Time_Start, 
    Recurrence.Recurrence_RecID, 
    RecurType, 
    RecurInterval, 
    DaysOfWeek, 
    AbsDayNbr, 
    SelectInterval, 
    NextAppointmentDate= 
    CASE 
     WHEN RecurType='m' THEN DATEADD(MONTH,RecurInterval,Resource.Date_Time_Start) 
     WHEN RecurType='y' THEN DATEADD(YEAR,RecurInterval,Resource.Date_Time_Start) 
    ELSE 
     NULL 
    END   
FROM 
    Recurrence 
    INNER JOIN Resource ON Resource.Recurrence_RecID=Recurrence.Recurrence_RecID 
    INNER JOIN service ON service.service_RecID=Resource.service_RecID 
    INNER JOIN customer ON customer.customer_ID=service.customerID 
)AS X 
WHERE 
    NextAppointmentDate>=GETDATE() 
ORDER BY Fields...