Advertisement
elena1234

How to Calculate Pay Period ( T- SQL )

Mar 27th, 2022
1,733
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
T-SQL 1.17 KB | None | 0 0
  1. -- Let's say your company pays once per month, on the 15th.
  2. -- If it's already the 15th of the current month (or later), the previous pay period will run from the 15th of the previous month,
  3. -- to the 14th of the current month.
  4. -- If on the other hand it's not yet the 15th of the current month, the previous pay period will run from the
  5. -- 15th two months ago to the 14th on the previous month.
  6. -- Set up variables defining the beginning and end of the previous pay period in this scenario.
  7. -- Select the variables to ensure they are working properly.
  8. DECLARE @Today DATE = CAST(GETDATE() AS DATE)
  9. SELECT @Today
  10. DECLARE @BeginningPayPeriod DATE
  11. DECLARE @EndPayPeriod DATE
  12. DECLARE @Current14 DATE = DATEFROMPARTS(YEAR(@Today),MONTH(@Today),14)
  13. DECLARE @Current15 DATE = DATEFROMPARTS(YEAR(@Today),MONTH(@Today),15)
  14.  
  15. SELECT @BeginningPayPeriod =
  16. CASE
  17. WHEN DAY(@Today) < 15
  18. THEN DATEADD(MONTH,-2, @Current15)
  19. ELSE DATEADD(MONTH,-1, @Current15)
  20. END
  21.  
  22. SELECT @EndPayPeriod =
  23. CASE
  24. WHEN DAY(@Today) >= 15
  25. THEN @Current14
  26. ELSE DATEADD(MONTH, - 1, @Current14)
  27. END
  28.  
  29.  
  30. SELECT
  31. *
  32. FROM AdventureWorks2019.dbo.Calendar
  33. WHERE DateValue BETWEEN @BeginningPayPeriod AND  @EndPayPeriod
  34.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement