UDF bernilai tabel

Menulis Function dan Stored Procedure di SQL Server

Meghan Kwartler

IT Consultant

Fungsi inline bernilai tabel (ITVF)

CREATE FUNCTION SumLocationStats (
  @StartDate AS datetime = '1/1/2017'
) RETURNS TABLE AS RETURN 
SELECT 
  PULocationID AS PickupLocation, 
  COUNT(ID) AS RideCount, 
  SUM(TripDistance) AS TotalTripDistance 
FROM YellowTripData 
WHERE CAST(PickupDate AS Date) = @StartDate 
GROUP BY PULocationID;
Menulis Function dan Stored Procedure di SQL Server
CREATE FUNCTION CountTripAvgFareDay (
  @Month char(2), 
  @Year char(4)
) RETURNS @TripCountAvgFare TABLE(
  DropOffDate date, TripCount int, AvgFare numeric
) AS BEGIN INSERT INTO @TripCountAvgFare 
SELECT 
  CAST(DropOffDate as date), 
  COUNT(ID), 
  AVG(FareAmount) as AvgFareAmt 
FROM YellowTripData 
WHERE 
  DATEPART(month, DropOffDate) = @Month 
  AND DATEPART(year, DropOffDate) = @Year 
GROUP BY CAST(DropOffDate as date)
RETURN END;
Menulis Function dan Stored Procedure di SQL Server

Perbedaan - ITVF vs. MSTVF

Inline

  • RETURN hasil SELECT
  • Nama kolom tabel di SELECT
  • Tanpa variabel tabel
  • Tidak perlu BEGIN END
  • Tanpa INSERT
  • Kinerja lebih cepat

Multi-statement

  • DECLARE variabel tabel yang akan dikembalikan
  • Blok BEGIN END wajib
  • INSERT data ke variabel tabel
  • RETURN pernyataan terakhir dalam blok BEGIN/END
Menulis Function dan Stored Procedure di SQL Server

Giliran Anda!

Menulis Function dan Stored Procedure di SQL Server

Preparing Video For Download...