質問

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