Date manipulation

Writing Functions and Stored Procedures in SQL Server

Meghan Kwartler

IT Consultant

GETDATE

SELECT GETDATE()
+-------------------------+
| 2019-02-27 13:11:59.590 |
+-------------------------+
DECLARE @CurrentDateTime AS datetime
SET @CurrentDateTime = GETDATE()
SELECT @CurrentDateTime
+-------------------------+
| 2019-02-27 13:14:36.517 |
+-------------------------+
Writing Functions and Stored Procedures in SQL Server
-- DATEADD Syntax:  
DATEADD (datepart, number, date)  
-- Returns expression based on data_type
-- One day after 2/27/2019
SELECT DATEADD(day, 1, '2/27/2019')
+-------------------------+
| 2019-02-28 00:00:00.000 |
+-------------------------+
Writing Functions and Stored Procedures in SQL Server

DATEADD and GETDATE

-- Yesterday
SELECT DATEADD(d, -1, GETDATE())
+-------------------------+
| 2019-02-26 09:20:50.013 |
+-------------------------+
-- Yesterday's Taxi Passenger Count
SELECT SUM(PassengerCount)
FROM YellowTripData
WHERE CAST(PickupDate as date) = DATEADD(d, -1, GETDATE())
Writing Functions and Stored Procedures in SQL Server

Remember DATEDIFF?

SELECT DATEDIFF(day, '2/27/2019', '2/28/2019')
+---+
| 1 |
+---+
SELECT DATEDIFF(year, '12/31/2017', '1/1/2019')
+---+
| 2 |
+---+
Writing Functions and Stored Procedures in SQL Server
-- First Day of Current Week
SELECT DATEADD(week, DATEDIFF(week, 0, GETDATE()), 0)
-- First step
GETDATE()
+-------------------------+
| 2019-02-27 10:33:39.713 |
+-------------------------+
-- How many weeks between today and 1/1/1900?
SELECT DATEDIFF(week, 0, GETDATE())
+------+
| 6217 |
+------+
Writing Functions and Stored Procedures in SQL Server
-- Add zero to the 6217nd week
SELECT DATEADD(week, DATEDIFF(week, 0, GETDATE()),0)
+-------------------------+
| 2019-02-25 00:00:00.000 |
+-------------------------+
Writing Functions and Stored Procedures in SQL Server

Now it's time for you to manipulate some dates!

Writing Functions and Stored Procedures in SQL Server

Preparing Video For Download...