UDFs are similar to stored procedures, where a user-defined function is an ordered set of T-SQL statements that are pre-optimized and compiled, and can be used as a unit to test calls. The main difference between UDFs and stored procedures is the way the results are returned, and in order to support more return values, UDFs are more restrictive than stored procedures.
UDF basic syntax: CREATE FUNCTION <function name> (< @parameter name> <data Type>[default VALUE][......N)
RETURNS < return type >
As Begin/* code */END
The simplest thing to try is a UDF:
CREATE FUNCTION Fun_getdatediff (@startDate datetime, @endDate datetime) returns Intas BEGIN return DateDiff (month, @startDate, @endDate); Endgoselect Productid,sum (LineTotal) from Purchasing.PurchaseOrderDetail where Dbo.fun_getdatediff (Duedate,getdate ( )) =142/**/ GROUP BY ProductID--142 of the data before the query
To modify the UDF: change the create directly to alter. UDFs are basically the same as stored procedures.
This chapter is relatively simple. Will not write too much, next to talk about business and locks. The feeling behind the writing is getting harder. A bit of an impulse to write.
SQL Getting Started Classic (ix) custom functions