2012-01-10 183 views
0

道歉的大規模愚蠢的問題,但我很好奇如何得到這個工作。目前我有一個查詢來查找我需要根據兩個日期之間的月份差異來更改的一些記錄。如何結合兩個sql腳本?

SELECT [MembershipTermID] 
    ,[MemberStatusProgKey] 
    ,[StartDate] 
    ,[EndDate] 
    ,[AdditionalDiscount] 
    ,[EntryDateTime] 
    ,[UpdateDateTime] 
    ,[MembershipID] 
    ,[AgentID] 
    ,[PlanVersionID] 
    ,[ForceThroughReference] 
    ,[IsForceThrough] 
    ,[NextTermPrePaid] 
    ,[IsBillingMonthly] 
    ,[CICSMEMBERNUM] 
    ,[CICSHISTORY] 
    ,[TMPSeqNoColumn] 
    ,[LastPaymentDate] 
    ,[PaidToDate] 
    ,[IsIndeterminate] 
    ,DATEDIFF(MONTH, PaidToDate, GETDATE()) as MonthsDifference 
FROM [Apollo].[dbo].[MembershipTerm] 
WHERE MemberStatusProgKey='DORMANT' AND IsBillingMonthly=1 AND DATEDIFF(MONTH, PaidToDate, GETDATE()) > 2 

但是我發現這個計算器上是拉兩個日期之間的確切差幾個月的正確方法:

CREATE FUNCTION FullMonthsSeparation 
(
@DateA DATETIME, 
@DateB DATETIME 
) 
RETURNS INT 
AS 
BEGIN 
DECLARE @Result INT 

DECLARE @DateX DATETIME 
DECLARE @DateY DATETIME 

IF(@DateA < @DateB) 
BEGIN 
    SET @DateX = @DateA 
    SET @DateY = @DateB 
END 
ELSE 
BEGIN 
    SET @DateX = @DateB 
    SET @DateY = @DateA 
END 

SET @Result = (
          SELECT 
          CASE 
            WHEN DATEPART(DAY, @DateX) > DATEPART(DAY, @DateY) 
            THEN DATEDIFF(MONTH, @DateX, @DateY) - 1 
            ELSE DATEDIFF(MONTH, @DateX, @DateY) 
          END 
          ) 

RETURN @Result 
END 
GO 

我怎樣才能將它們組合起來,所以我基本上是計算滿月差但從WHERE子句部分?

回答

3

一旦你在你的FullmonthsSeperation功能的數據庫運行,你只需要調用它像這樣:

SELECT [MembershipTermID] 
    ,[MemberStatusProgKey] 
    ,[StartDate] 
    ,[EndDate] 
    ,[AdditionalDiscount] 
    ,[EntryDateTime] 
    ,[UpdateDateTime] 
    ,[MembershipID] 
    ,[AgentID] 
    ,[PlanVersionID] 
    ,[ForceThroughReference] 
    ,[IsForceThrough] 
    ,[NextTermPrePaid] 
    ,[IsBillingMonthly] 
    ,[CICSMEMBERNUM] 
    ,[CICSHISTORY] 
    ,[TMPSeqNoColumn] 
    ,[LastPaymentDate] 
    ,[PaidToDate] 
    ,[IsIndeterminate] 
    ,DATEDIFF(MONTH, PaidToDate, GETDATE()) as MonthsDifference 
FROM [Apollo].[dbo].[MembershipTerm] 
WHERE MemberStatusProgKey='DORMANT' 
AND IsBillingMonthly=1 
AND dbo.FullMonthsSeparation (PaidToDate, GETDATE()) > 2 
+0

非常感謝您StevieG,正是我一直在尋找。 – shicky 2012-01-10 14:49:06