Variables for datetime data

Writing Functions and Stored Procedures in SQL Server

Meghan Kwartler

IT Consultant

Lockers

Writing Functions and Stored Procedures in SQL Server
-- DECLARE variable and assign initial value
 DECLARE @StartTime as time = '08:00 AM'
-- DECLARE variable and then SET value
DECLARE @StartTime AS time 
SET @StartTime = '08:00 AM'
-- DECLARE variable then SET value
DECLARE @BeginDate as date 
SET 
  @BeginDate = (
    SELECT TOP 1 PickupDate 
    FROM YellowTripData 
    ORDER BY PickupDate ASC
  );
Writing Functions and Stored Procedures in SQL Server

CASTing

-- CAST syntax
CAST ( expression AS data_type [ ( length ) ] ) 
-- Returns expression based on data_type
-- DECLARE datetime variable
-- SET value to @BeginDate and @StartTime while CASTing
DECLARE @StartDateTime as datetime 
SET @StartDateTime = CAST(@BeginDate as datetime) + CAST(@StartTime as datetime)
Writing Functions and Stored Procedures in SQL Server
-- DECLARE table variable with two columns
DECLARE @TaxiRideDates TABLE(
    StartDate date,
    EndDate date)
-- INSERT static values into table variable
INSERT INTO @TaxiRideDates (StartDate, EndDate)
SELECT '3/1/2018', '3/2/2018'
-- INSERT query result
INSERT INTO @TaxiRideDates(StartDate, EndDate)
SELECT DISTINCT
    CAST(PickupDate  as date), 
    CAST(DropOffDate  as date)
    FROM YellowTripData;
Writing Functions and Stored Procedures in SQL Server

Your turn to DECLARE, SET, CAST & INSERT!

Writing Functions and Stored Procedures in SQL Server

Preparing Video For Download...