User-defined function

This is an old revision of this page, as edited by Mikeblas (talk | contribs) at 14:59, 18 June 2006 (Databases: spelling, clarification). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

A User Defined Function, or UDF, is a function provided by the user of a program or environment, in a context where the usual assumption is that functions are built into the program or environment.

BASIC language

In some old implementations of the BASIC programming language, user defined functions are defined using the "DEF FN" syntax. More modern dialects of BASIC are influenced by the structured programming paradigm, where most or all code is written as user defined functions or procedures, and the concept becomes practically redundant.


Databases

In SQL Databases, a user-defined function provides a mechanism for extending to the database server by adding a function that can evaluated in SQL queries. User defined functions in SQL are declared using the CREATE FUNCTION keywords. For example, a function that converts Celsius to Fahrenheit might be declared like this:

CREATE FUNCTION CtoF(@Celsius FLOAT)
RETURNS FLOAT
AS
BEGIN
	return (@Celsius * 1.8) + 32
END

Once created, the user-defined function may be invoked where most other intrinsic functions are available. This includes SELECT statements, where the function can be used against data stored in the database. In such usage, the function is evaluated once per row. For example, assume a table named ELEMENTS, with a row for each known chemical element. The table has a column named BoilingPoint for the boiling point of that element, in Celsius. This query:

SELECT Name, CtoF(BoilingPoint)
  FROM Elements

would retrieve the name and the boiling point from each row. It invokes the CtoF user-defined function we've declared above in order to convert the value in the column to a value in Fahrenheit.

User-defined functions should not be confused with stored procedures. Stored procedures allow the user to create a set of SQL commands that accept parameters and can be executed using those parameters. These procedures run as a set and return a set of rows; they are not evaluated per-row in any circumstance, as user-defined functions are.

Some database management systems allow the creation of user defined functions in languages other than SQL. Mirosoft SQL Server, for example, allows the user to use .NET languages for this purpose.