Intro

There are two kinds of functions supported in SQL Server:

Functions are also either deterministic or non-deterministic. A deterministic function always returns the same results when fed the same arguments. A non-deterministic function may return different results for the same set of arguments.

This section was done for SQL Server 2000. I haven't stuck in stuff for SQL Server 2005 yet.

User-Defined

A user-defined function take parameters and returns a single value. There are three kinds of user-defined functions:

Here is the syntax for creating user-defined functions:

CREATE FUNCTION [OwnerName.]FunctionName     ([{@ParameterName [AS] ScalarParameterDataType[ = Default]}[, ...]])
--Scalar Functions:
RETURNS ScalarReturnDataType
[WITH {ENCRYPTION | SCHEMABINDING}[[,] ...]]
[AS]
BEGIN
    FunctionBody
    RETURN ScalarExpression
END
--Inline Table-Valued Functions:
RETURNS TABLE
[WITH {ENCRYPTION | SCHEMABINDING}[[,] ...]]
[AS]
RETURN [(]
    SELECTStatement
[)]
--Multi-Statement Table-Valued Functions:
RETURNS @ReturnTableVariable TABLE TableDefinition
[WITH {EnCRYPTION | SCHEMABINDING}[[,] ...]]
[AS]
BEGIN
    FunctionBody
    RETURN
END

Here are some general notes on user-defined functions:

EG Scalar User-Defined Function

This cubes a number:

CREATE FUNCTION FCubeMe(@SideOfCube float)
RETURNS float
AS
BEGIN
    RETURN (@SideOfCube * @SideOfCube * @SideOfCube)
END

EG Inline Table-Valued User-Defined Function

This makes a simple table:

CREATE FUNCTION FSomeTable(@State char(2))
RETURNS TABLE
AS
RETURN(SELECT * FROM tbl1 WHERE state = @State)

Aggregate

Aggregate functions return a single value based on applicable rows. Aggregate functions cannot be combined with simple column names in a SelectList, that return multiple values. Except for COUNT(*), all the aggregate functions ignore nulls.

These functions are all deterministic.

AVG MAX
BINARY_CHECKSUM MIN
CHECKSUM SUM
CHECKSUM_AGG STDEV
COUNT STDEVP
COUNT_BIG VAR
GROUPING VARP

Here is syntax (where expression is almost always a column name) for some of the more popular ones:

SUM ([ALL | DISTINCT] expression)
AVG ([ALL | DISTINCT] expression)
COUNT ([ALL | DISTINCT] expression)
COUNT(*) --Number of rows, even nulls
MAX(expression)
MIN(expression)

Examples:

SELECT SUM(price), COUNT(*), AVG(price), MAX(price), MIN(price)
FROM tbl1 WHERE price > 5
--If tbl1 has prices of 1 thru 10, then it returns this: --sum of 40, count of 5, avg of 8, max of 10, min of 5.

Configuration

These return info about current configuration option settings.

These functions are all non-deterministic.

@@DATEFIRST @@OPTIONS
@@DBTS @@REMSERVER
@@LANGID @@SERVERNAME
@@LANGUAGE @@SERVICENAME
@@LOCK_TIMEOUT @@SPID
@@MAX_CONNECTIONS @@TEXTSIZE
@@MAX_PRECISION @@VERSION
@@NESTLEVEL  

Cursor

These return info about cursors.

These functions are all non-deterministic.

@@CURSOR_ROWS
CURSOR_STATUS
@@FETCH_STATUS

Date and Time

Date and time related thingies in SQL Server. The functions are all deterministic except for DATENAME, GETDATE, GETUTCDATE.

Here are the values for DatePart accepted by SQL Server. Note that weekday is not usually used in DATEADD() or DATEDIFF().

DatePart Abbreviations Values
year yy, yyyy 1900-9999
quarter qq, q 1-3
month mm, m 1-3
dayofyear dy, y 1-366
day dd, d 1-31
weekday dw 1-7 (Mon.-Sun.)
week wk, ww 1-53
hour hh 0-23
minute mi, n 0-59
second ss, s 0-59
millisecond ms 0-999

Date Time Details

Mathematical

Except for RAND, these functions are all non-deterministic.

ABS DEGREES RAND
ACOS EXP ROUND
ASIN FLOOR SIGN
ATAN LOG SIN
ATN2 LOG10 SQUARE
CEILING PI SQRT
COS POWER TAN
COT RADIANS  

Meta Data

These return info about the database and database objects.

These functions are all non-deterministic.

COL_LENGTH fn_listextendedproperty
COL_NAME FULLTEXTCATALOGPROPERTY
COLUMNPROPERTY FULLTEXTSERVICEPROPERTY
DATABASEPROPERTY INDEX_COL
DATABASEPROPERTYEX INDEXKEY_PROPERTY
DB_ID INDEXPROPERTY
DB_NAME OBJECT_ID
FILE_ID OBJECT_NAME
FILE_NAME OBJECTPROPERTY
FILEGROUP_ID @@PROCID
FILEGROUP_NAME SQL_VARIANT_PROPERTY
FILEGROUPPROPERTY TYPEPROPERTY
FILEPROPERTY  

Rowset

These return objects that can be used in place of a table. These are great!

These functions are all non-deterministic.

CONTAINSTABLE
FREETEXTTABLE
OPENDATASOURCE
OPENQUERY
OPENROWSET
OPENXML

Security

These return info about users and roles.

These functions are all non-deterministic.

fn_trace_geteventinfo IS_SRVROLEMEMBER
fn_trace_getfilterinfo SUSER_SID
fn_trace_getinfo SUSER_SNAME
fn_trace_gettable USER_ID
HAS_DBACCESS USER
IS_MEMBER  

String

These take a string and return a string or numeric result. These are great! Except for CHARINDEX and PATINDEX, these functions are all non-deterministic.

String related thingies in SQL Server.

System

These do things and get info about SQL Server.

Function Determinism
APP_NAME Nondeterministic
CASE expression Deterministic
CAST and CONVERT Deterministic unless used with datetime, smalldatetime, or sql_variant.
COALESCE Deterministic
COLLATIONPROPERTY Nondeterministic
CURRENT_TIMESTAMP Nondeterministic
CURRENT_USER Nondeterministic
DATALENGTH Deterministic
@@ERROR Nondeterministic
fn_helpcollations Deterministic
fn_servershareddrives Nondeterministic
fn_virtualfilestats Nondeterministic
FORMATMESSAGE Nondeterministic
GETANSINULL Nondeterministic
HOST_ID Nondeterministic
HOST_NAME Nondeterministic
IDENT_CURRENT Nondeterministic
IDENT_INCR Nondeterministic
IDENT_SEED Nondeterministic
@@IDENTITY Nondeterministic
IDENTITY (Function) Nondeterministic
ISDATE Deterministic only if used with the CONVERT function, the CONVERT style parameter is specified and the style parameter is not equal to 0, 100, 9, or 109. Styles 0 and 100 use the default format mon dd yyyy hh:miAM (or PM). Styles 9 and 109 use the default format plus milliseconds mon dd yyyy hh:mi:ss:mmmAM (or PM).
ISNULL Deterministic
ISNUMERIC Deterministic
NEWID Nondeterministic
NULLIF Deterministic
PARSENAME Deterministic
PERMISSIONS Nondeterministic
@@ROWCOUNT Nondeterministic
ROWCOUNT_BIG Nondeterministic
SCOPE_IDENTITY Nondeterministic
SERVERPROPERTY Nondeterministic
SESSIONPROPERTY Nondeterministic
SESSION_USER Nondeterministic
STATS_DATE Nondeterministic
SYSTEM_USER Nondeterministic
@@TRANCOUNT Nondeterministic
USER_NAME Nondeterministic

CAST and CONVERT Syntax:

CONVERT(DataType[(length)], expression [, style])
--A SQL Server function.
CAST(Expression AS DataType)
--Preferred since this works for both SQL-92 & SQL Server.

System Statistical

These return statistical info about the system.

These functions are all non-deterministic.

@@CONNECTIONS @@PACK_RECEIVED
@@CPU_BUSY @@PACK_SENT
fn_virtualfilestats @@TIMETICKS
@@IDLE @@TOTAL_ERRORS
@@IO_BUSY @@TOTAL_READ
@@PACKET_ERRORS @@TOTAL_WRITE

Text and Image

These operate on text or image values and return statistical info about the value.

These functions are all non-deterministic.

PATINDEX
TEXTPTR
TEXTVALID

Page Modified: (Hand noted: 2007-10-12 21:45:09Z) (Auto noted: 2008-06-04 14:55:04Z)