Advertisement
elena1234

Create Function with Parameters ( T-SQL )

Mar 27th, 2022
1,666
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
T-SQL 0.99 KB | None | 0 0
  1. --Correlated Subquery Example:
  2.  
  3. SELECT
  4.       SalesOrderID,
  5.       OrderDate,
  6.       DueDate,
  7.       ShipDate,
  8.       ElapsedBusinessDays = (
  9.         SELECT
  10.         COUNT(*)
  11.         FROM AdventureWorks2019.dbo.Calendar B
  12.         WHERE B.DateValue BETWEEN A.OrderDate AND A.ShipDate
  13.             AND B.WeekendFlag = 0
  14.             AND B.HolidayFlag = 0
  15.       )
  16.  
  17. FROM AdventureWorks2019.Sales.SalesOrderHeader A
  18. WHERE YEAR(A.OrderDate) = 2011
  19.  
  20.  
  21. --Rewriting as a function, with variables:
  22.  
  23. CREATE FUNCTION dbo.ufnElapsedBusinessDays(@StartDate DATE, @EndDate DATE)
  24. RETURNS INT
  25. AS  
  26. BEGIN
  27.     RETURN
  28.         (
  29.             SELECT
  30.                 COUNT(*)
  31.             FROM AdventureWorks2019.dbo.Calendar
  32.  
  33.             WHERE DateValue BETWEEN @StartDate AND @EndDate
  34.                 AND WeekendFlag = 0
  35.                 AND HolidayFlag = 0
  36.         )  
  37. END
  38.  
  39.  
  40. --Using the function in a query
  41.  
  42. SELECT
  43.       SalesOrderID,
  44.       OrderDate,
  45.       DueDate,
  46.       ShipDate,
  47.       ElapsedBusinessDays = dbo.ufnElapsedBusinessDays(OrderDate,ShipDate)
  48. FROM AdventureWorks2019.Sales.SalesOrderHeader
  49. WHERE YEAR(OrderDate) = 2011
  50.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement