Advertisement
sunraycafe

T-SQL Date Math

May 12th, 2017
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
T-SQL 1.96 KB | None | 0 0
  1. /*------------------------------------------------------------------------------
  2.     WORKING WITH DATES AND MATH
  3.  
  4.     I'd previously been led to believe the only way to add and subtract from
  5.     dates was to use the DATEADD() function. I recently discovered that's not
  6.     true. The trick is to make sure the date you're working with is of type
  7.     datetime, and not just date.
  8.  
  9. ------------------------------------------------------------------------------*/
  10.  
  11. -- Here are some examples of subtracting time from a datetime value
  12. -- Notice the math has to be decimal math, not integer, or it won't work
  13. select getdate()
  14. select cast('10-MAY-2017' as datetime)                          -- midnight
  15. select cast('10-MAY-2017' as datetime) - 1*(1/24.0/60.0)        -- midnight minus 1 minute
  16. select cast('10-MAY-2017' as datetime) - 1*(1/24.0/60.0/60.0)   -- midnight minus 1 second
  17.  
  18. -- Another thing I noticed in this testing was that SELECT and PRINT show
  19. -- the same value two different ways. PRINT excludes the seconds and milliseconds
  20. select getdate()
  21. print getdate()
  22.  
  23. -- You can display the detailed data using PRINT if you convert it to a varchar,
  24. -- but you cannot do math against a varchar. You can do math if you convert it to
  25. -- datetime, but then you can't see the details again.
  26. print convert(varchar(24),getdate(),109)                        -- shows seconds, no math
  27. print convert(varchar(24),getdate(),109) - 1*(1/24.0/60.0)      -- this line won't work
  28. print convert(datetime,getdate(),109) - 1*(1/24.0/60.0)         -- can math, no seconds
  29.  
  30. -- You can use the other datetime formats as well, but keep in mind the
  31. -- specific limitations/features of each type.
  32. select getdate()
  33. select cast(getdate() as smalldatetime)                         -- rounds to nearest whole minute
  34. select cast(getdate() as smalldatetime) - 1*(1/24.0/60.0)       -- subtract one minute
  35. select cast(getdate() as smalldatetime) - 1*(1/24.0/60.0/60.0)  -- subtract one second, no difference
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement