Microsoft SQL Server 2005 Best Practices

How to create a counting function?

 

Execute the following script in Query Editor to count the number of purchase orders issued by an employee:

USE AdventureWorks;

CREATE FUNCTION
fnPurchaseOrdersByEmployee(@EmpID INT)
RETURNS INT
AS
BEGIN
RETURN
(
SELECT COUNT(*) AS
'PurchaseOrdersByEmployee'
FROM Purchasing.PurchaseOrderHeader
WHERE EmployeeID = @EmpID
GROUP BY EmployeeID
)
END

-- SELECT EmployeeID, [PO-s] = dbo.fnPurchaseOrdersByEmployee(EmployeeID) FROM HumanResources.Employee ORDER BY EmployeeID

 

 

The Best SQL Server 2005 Training in the World
 
 
SQLUSA.com Home Page