Writing Functions and Stored Procedures in SQL Server
Meghan Kwartler
IT Consultant
-- 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
);
-- 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)
-- 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