Beruflich Dokumente
Kultur Dokumente
Each new version of SQL Server features improvements to T-SQL that make
development easier. SQL Server 2000 introduced (among other things) the concept of
user-defined functions (UDFs). Like functions in other programming languages, T-SQL
UDFs provide
a convenient way for developers to define routines that accept parameters, perform
actions based on those parameters, and return data to the caller. T-SQL functions come in
three flavors: inline table-valued functions (TVFs), multistatement TVFs, and scalar
functions. SQL Server 2014 also supports the ability to create CLR integration UDFs,
which are discussed in Chapter 15.
Scalar Functions
Basically, a scalar UDF is a function that accepts zero or more parameters and returns a
single scalar value as the result. Youre probably already familiar with scalar functions
in mathematics, and with T-SQLs built-in scalar functions (such as ABS and
SUBSTRING). The CREATE FUNCTION statement allows you to create custom scalar
functions that behave like the built-in scalar functions.
To demonstrate scalar UDFs, lets a trip back in time to high school geometry class.
In accordance with the rules passed down from Euclid, this UDF accepts a circles radius
and returns the area of the circle using the formula area = r2. Listing 4-1 demonstrates
this simple scalar UDF.
Listing 4-1. Simple Scalar UDF
CREATE FUNCTION dbo.CalculateCircleArea (@Radius float =1.0)
RETURNS float
WITH RETURNS NULL ON NULL INPUT
AS
BEGIN
RETURN PI() * POWER(@Radius, 2);
END;
The first line of the CREATE FUNCTION statement defines the schema and name of
the function using a standard SQL Server two-part name
(dbo.CalculateCircleArea) and a single required parameter, the radius of the
circle (@Radius). The @Radius parameter is defined as a T-SQL float type. The
parameter is assigned a default value of 1.0 by the = 1.0 after the parameter
declaration:
CREATE FUNCTION dbo.CalculateCircleArea (@Radius float =1.0)
The next line contains the RETURNS keyword, which specifies the data type of the
result that will be returned by the UDF. In this instance, the RETURNS keyword
indicates that the UDF will return a float result:
RETURNS float
The third line contains additional options following the WITH keyword. The example
uses the RETURNS NULL ON NULL INPUT function option for a performance
improvement. The RETURNS NULL ON NULL INPUT option is a performanceenhancing option that automatically returns NULL if any of the parameters passed in are
NULL. The performance enhancement occurs because SQL Server wont execute the
body of the function if a NULL is passed in and this option is specified:
WITH RETURNS NULL ON NULL INPUT
The AS keyword indicates the start of the function body which must be enclosed in
the T-SQL BEGIN and END keywords. The sample function in Listing 4-1 is very simple,
consisting of a single RETURN statement that immediately returns the value of the circle
area calculation. The RETURN statement must be the last statement before the END
keyword in every scalar UDF:
RETURN PI() * POWER(@radius, 2);
You can test this simple UDF with a few SELECT statements like the following.
The results are shown in Figure 4-1:
SELECT dbo.CalculateCircleArea(10);
SELECT dbo.CalculateCircleArea(NULL);
SELECT dbo.CalculateCircleArea(2.5);
UDF PARAMETERS
UDF parameters operate similarly to, but slightly differently from, stored procedure
(SP) parameters. Its important to be aware of the differences. For instance, if you
create a UDF that accepts no parameters, you still need to include empty
parentheses after the function nameboth when creating and when invoking the
function. Some built-in functions, like the PI() function used in Listing 4-1, which
represents the
UDF ENCRYPTION
Using the ENCRYPTION option on UDFs performs a simple
obfuscation of your code. It actually does little more than keep
honest people honest, and in reality it tends to be more trouble
than its worth. Many developers and DBAs have spent precious
time scouring the Internet for tools to decrypt their database
objects because they were convinced the scripts in their source
control database were out of sync with the production database.
Keep in mind that those same decryption tools are available to
anyone with an Internet connection and a browser. If you write
commercial database scripts or perform database consulting
services, your best (and really only) protection against curious
DBAs and developers reverse-engineering and modifying your
code is a well-written contract. Keep this in mind when deciding
whether to encrypt your database objects.
Funciones definidas por el usuario
4
Cada nueva versin de SQL Server incluye diversas mejoras en T-SQL que hacen ms fcil el desarrollo.
SQL Server 2000 introduce (entre otras cosas) el concepto de funciones definidas por el usuario (UDF).
Como funciones en otros lenguajes de programacin, UDF T-SQL proporcionan
una manera conveniente para los desarrolladores para definir rutinas que aceptan parmetros, realice las
acciones basadas en esos parmetros, y devolver los datos a la persona que llama. Funciones T-SQL
vienen en tres sabores: funciones en lnea con valores de tabla (TVF), TVF varias instrucciones y
funciones escalares. SQL Server 2014 tambin es compatible con la capacidad de crear las UDF de
integracin CLR, que se discuten en el Captulo 15.
Funciones escalares
Bsicamente, una UDF escalar es una funcin que acepta cero o ms parmetros y devuelve un solo valor
escalar como el resultado. Probablemente usted est familiarizado con las funciones escalares en
matemticas, y con una funcin de funciones escalares (como ABS y SUBSTRING) de T-SQL. La
sentencia CREATE FUNCTION permite crear funciones a medida escalares que se comportan como la
incorporada en funciones escalares.
Para demostrar las UDF escalares, vamos a un viaje en el tiempo a la clase de geometra de la escuela
secundaria. De acuerdo con las normas transmitidas de Euclides, esta UDF acepta el radio de un crculo y
devuelve el rea del crculo utilizando el rea frmula = r2. Listado 1.4 muestra esta sencilla UDF
escalar.