Maintaining user defined functions

Writing Functions and Stored Procedures in SQL Server

Meghan Kwartler

IT Consultant

ALTER Function

ALTER FUNCTION SumLocationStats (@EndDate as datetime = '1/01/2017')
RETURNS TABLE AS RETURN 
SELECT 
  PULocationID as PickupLocation, 
  COUNT(ID) as RideCount, 
  SUM(TripDistance) as TotalTripDistance 
FROM YellowTripData 
WHERE CAST(DropOffDate as Date) = @EndDate 
GROUP BY PULocationID;
Writing Functions and Stored Procedures in SQL Server

CREATE OR ALTER

CREATE OR ALTER FUNCTION SumLocationStats (
 @EndDate AS datetime = '1/01/2017') 
 RETURNS TABLE AS RETURN 
SELECT 
  PULocationID as PickupLocation, 
  COUNT(ID) AS RideCount, 
  SUM(TripDistance) AS TotalTripDistance 
FROM YellowTripData 
WHERE CAST(DropOffDate AS Date) = @EndDate 
GROUP BY PULocationID;
Writing Functions and Stored Procedures in SQL Server
-- Delete function
DROP FUNCTION dbo.CountTripAvgFareDay
-- Create CountTripAvgFareDay as Inline TVF instead of MSTVF
CREATE FUNCTION dbo.CountTripAvgFareDay(
  @Month char(2), 
  @Year char(4)
) RETURNS TABLE AS RETURN (
  SELECT 
    CAST(DropOffDate as date) as DropOffDate, 
    COUNT(ID) as TripCount, 
    AVG(FareAmount) as AvgFareAmt 
  FROM YellowTripData 
  WHERE 
    DATEPART(month, DropOffDate) = @Month 
    AND DATEPART(year, DropOffDate) = @Year 
  GROUP BY CAST(DropOffDate as date));
Writing Functions and Stored Procedures in SQL Server

Determinism improves performance

  • A function is deterministic when it returns the same result given
    • the same input parameters
    • the same database state
Writing Functions and Stored Procedures in SQL Server
SELECT 
  OBJECTPROPERTY(
    OBJECT_ID('[dbo].[GetRideHrsOneDay]'), 
    'IsDeterministic'
  )
+---+
| 1 |
+---+
SELECT 
  OBJECTPROPERTY(
    OBJECT_ID('[dbo].[GetTomorrow]'), 
    'IsDeterministic'
  )
+---+
| 0 |
+---+
Writing Functions and Stored Procedures in SQL Server

Schemabinding

  • Specifies the schema is bound to the database objects that it references
  • Prevents changes to the schema if schema bound objects are referencing it
CREATE OR ALTER FUNCTION dbo.GetRideHrsOneDay (@DateParm date)
RETURNS numeric WITH SCHEMABINDING
AS
BEGIN
RETURN 
(SELECT SUM(DATEDIFF(second, PickupDate, DropoffDate))/3600
FROM dbo.YellowTripData
WHERE CONVERT (date, PickupDate) = @DateParm)
END;
Writing Functions and Stored Procedures in SQL Server

Let's practice!

Writing Functions and Stored Procedures in SQL Server

Preparing Video For Download...