如何结合两个sql脚本?

时间:2012-01-10 03:02:58

标签: sql sql-server

为这个大笨拙的问题道歉,但我很好奇如何让它发挥作用。目前,我有一个查询,要根据两个日期之间的月份差异找到我需要更改的一些记录。

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

但是我在stackoverflow上找到了这个,这是正确的方法来拉出两个日期之间的确切月份差异:

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子句部分计算完整的月份差异?

1 个答案:

答案 0 :(得分: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