문제

This is my first question so hope its all good!

What I have done is a user-defined (table valued) function using MSSMS, where in one point, I have to find records based on the functions parameter @Year.

Problem for me arises when records are older than two years, then it should list all the record which are older than two years. I have been banging my head on the wall with this one, and this is where I have gotten so far:

WHERE   (
        @Year = YEAR(GETDATE()) AND YEAR(E.ExampleColumnDate) = @Year
        OR
        @Year = YEAR(GETDATE())-1 AND YEAR(E.ExampleColumnDate) = @Year
        OR
        @Year = YEAR(GETDATE())-2 AND YEAR(E.ExampleColumnDate) = @Year
        OR
        @Year <= YEAR(GETDATE())-3 AND YEAR(E.ExampleColumnDate) < @Year
        )
도움이 되었습니까?

해결책

WHERE   (
        (@Year = YEAR(GETDATE()) AND YEAR(E.ExampleColumnDate) = @Year)
        OR
        (@Year = YEAR(GETDATE())-1 AND YEAR(E.ExampleColumnDate) = @Year)
        OR
        (@Year = YEAR(GETDATE())-2 AND YEAR(E.ExampleColumnDate) = @Year)
        OR
        (@Year <= YEAR(GETDATE())-3 AND YEAR(E.ExampleColumnDate) < @Year)
        )

다른 팁

you can get records are older than two years with this also

;with cte 
as
(
SELECT top 10 DATEDIFF(year,E.ExampleColumnDate, getdate()) as diff, * 
  FROM [yourtablename]
  )
  select * from cte where diff =2
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top