SQL Server User Defined Functions
CREATE FUNCTION [ schema_name. ] function_name ( [ [ AS ][ type_schema_name. ] parameter_data_type [ = default ] [ READONLY ] } [,...n ] ]) RETURNS return_data_type [ WITH [,...n ] ] [ AS ] BEGIN function_body RETURN scalar_expression END
CREATE FUNCTION [ schema_name. ] function_name ( [ [ AS ] [ type_schema_name. ] parameter_data_type [ = default ] [ READONLY ] } [,...n ] ]) RETURNS TABLE [ WITH [,...n ] ] [ AS ] RETURN [ ( ] select_stmt [ ) ]
CREATE FUNCTION [ schema_name. ] function_name ( [ [ AS ] [ type_schema_name. ] parameter_data_type [ = default ] [READONLY] } [,...n ] ]) TABLE [ WITH [,...n ] ] [ AS ] BEGIN function_body RETURN END
CREATE FUNCTION Orders.fn_oldestopenorder() RETURNS INT AS BEGIN DATE = MIN(OrderDate) FROM Orders.OrderHeader WHERE FinalShipDate IS NULL = MIN(OrderID) FROM Orders.OrderHeader WHERE OrderDate END GO
CREATE FUNCTION Orders.fn_openorders INT) RETURNS TABLE AS RETURN (SELECT OrderID, CustomerID, OrderDate FROM Orders.OrderHeader WHERE OrderDate <= AND FinalShipDate IS NULL) GO
CREATE FUNCTION INT) TABLE (OrderID INT NOT NULL, CustomerID INT NOT NULL, OrderDate DATE NOT NULL) AS BEGIN TABLE (OrderID INT NOT NULL, CustomerID INT NOT NULL, OrderDate DATE NOT NULL) INSERT (OrderID, CustomerID, OrderDate) SELECT OrderID, CustomerID, OrderDate FROM INSERT (OrderID, CustomerID, OrderDate) SELECT a.OrderID, a.CustomerID, a.OrderDate a INNER JOIN (SELECT OrderID FROM Orders.OrderDetail EXCEPT SELECT OrderID FROM Orders.OrderDetail c INNER JOIN Products.ProductOptions d ON c.SKU = d.SKU INNER JOIN Products.ProductInventory e ON d.ProductID = e.ProductID WHERE c.Quantity >= e.Quantity) b ON a.OrderID = b.OrderID RETURN END GO
USE AdventureWorks2008 GO CREATE FUNCTION dbo.fnContactList() RETURNS TABLE 416 Chapter 13: User-Defined Functions AS RETURN (SELECT BusinessEntityID, LastName + ‘, ‘ + FirstName AS Name FROM Person.Person); GO SELECT * FROM dbo.fnContactList();
USE AdventureWorks2008; GO CREATE FUNCTION nvarchar(50)) RETURNS TABLE AS RETURN (SELECT p.BusinessEntityID, LastName + ‘, ‘ + FirstName AS Name, ea. Address FROM Person.Person as p LEFT OUTER JOIN Person. Address ea ON ea.BusinessEntityID = p.BusinessEntityID WHERE LastName + ‘%’); GO
SELECT * FROM fnContactSearch(‘Ad’);
CREATE FUNCTION dbo.AveragePrice() RETURNS money WITH SCHEMABINDING AS BEGIN RETURN (SELECT AVG(ListPrice) FROM Production.Product); END GO CREATE FUNCTION money) RETURNS money AS BEGIN - dbo.AveragePrice(); END