Guest User

Untitled

a guest
Jan 16th, 2019
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. SELECT
  2. ....
  3. FROM
  4. ....
  5. WHERE
  6. (CAST((DATEDIFF(dd, Invoice.DateOpened @EndDate)/30) AS INT) - CAST((DATEDIFF(dd, Invoice.DateOpened, @StartDate)/30) AS INT)) >=1
  7. OR DATEDIFF(dd, Invoice.DateOpened, @StartDate) % 30 = 0 --this line to capture valid records but where From and To dates are the same
  8.  
  9. SELECT
  10. ....
  11. FROM
  12. ....
  13. WHERE
  14. --In MS T-SQL, BETWEEN is inclusive.
  15. DateOpened BETWEEN @UserSuppliedFromDate AND @UserSuppliedToDate
  16. AND DATEDIFF(dd, DateOpened, getdate()) % 30 = 0
  17.  
  18. DECLARE @Table TABLE
  19. (
  20. ID integer,
  21. DateOpened datetime
  22. )
  23.  
  24. DECLARE @FromDate as datetime = '1/1/2012'
  25. DECLARE @ToDate as datetime = '12/31/2012'
  26.  
  27. INSERT INTO @Table VALUES (0, '1/1/1982')
  28. INSERT INTO @Table values (1, '1/1/2012')
  29. INSERT INTO @Table VALUES (2, '2/17/2012')
  30. INSERT INTO @Table VALUES (3, '3/16/2012')
  31. INSERT INTO @Table VALUES (4, '4/16/2012')
  32. INSERT INTO @Table VALUES (5, '5/28/2012')
  33. INSERT INTO @Table VALUES (6, '1/31/2012')
  34. INSERT INTO @Table VALUES (7, '12/12/2013')
  35.  
  36. DECLARE @DateLoop as datetime
  37. DECLARE @ResultIDs as table ( ID integer, DateLoopAtTheTime datetime, DaysDifference integer )
  38.  
  39. --Initialize to lowest possible value
  40. SELECT @DateLoop = @FromDate
  41.  
  42. --Loop until we hit the maximum date to check
  43. WHILE @DateLoop <= @ToDate
  44. BEGIN
  45. INSERT INTO @ResultIDs (ID,DateLoopAtTheTime, DaysDifference)
  46. SELECT ID, @DateLoop, DATEDIFF(dd,@DateLoop, DateOpened)
  47. FROM @Table
  48. WHERE
  49. DATEDIFF(dd,@DateLoop, DateOpened) % 30 = 0
  50. AND DATEDIFF(dd,@DateLoop,DateOpened) > 0 -- Avoids false positives when @DateLoop and DateOpened are the same
  51. AND DateOpened <= @ToDate
  52. SELECT @DateLoop = DATEADD(dd, 1, @DateLoop) -- Increment the iterator
  53. END
  54.  
  55. SELECT distinct * From @ResultIDs
Add Comment
Please, Sign In to add comment