Sie sind auf Seite 1von 6

User-Defined Functions

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);

Figure 4-1. The results of the sample circle area calculations

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

value of the constant (3.14159265358979), dont take parameters. Notice that


when the function is called in the UDF, its still called with empty parentheses.
When SPs are assigned default values, you can simply leave the parameter off
your parameter list completely when calling the procedure. This isnt an option
with UDFs. To use a UDF default value, you must use the DEFAULT keyword
when calling the UDF. To use the default value for the @radius parameter of the
example
dbo.CalculateCircleArea UDF, you call the UDF like this:
SELECT dbo.CalculateCircleArea (DEFAULT);
Finally, SPs have no equivalent to the RETURNS NULL ON NULL INPUT option.
You can simulate this functionality to some extent by checking your parameters for
NULL immediately on entering the SP, though. SPs are discussed in greater detail in
Chapter 5.
UDFs provide several creation-time options that allow you to improve
performance and security, including the following:
The ENCRYPTION option can be used to store your UDF in the
database in obfuscated format. Note that this isnt true encryption, but
rather an easily circumvented obfuscation of your code. See the
UDF
Encryption sidebar for more information.
The SCHEMABINDING option indicates that your UDF will be bound
to database objects referenced in the body of the function. With
SCHEMABINDING turned on, attempts to change or drop referenced
tables and other database objects result in an error. This helps to
prevent inadvertent changes to tables and other database objects that
can break your UDF. Additionally, the SQL Server Database Engine
team has published information indicating that SCHEMABINDING can
improve the performance of UDFs, even if they dont reference other
database objects
(http://blogs.msdn.com/b/sqlprogrammability/archive/2
The CALLED ON NULL INPUT option is the opposite of RETURNS
NULL ON NULL INPUT. When CALLED ON NULL INPUT is
specified, SQL Server executes the body of the function even if one
or more parameters are NULL. CALLED ON NULL INPUT is a
default option for all scalar-valued functions.
The EXECUTE AS option manages caller security on UDFs. You
can specify that the UDF be executed as any of the following:
CALLER indicates that the UDF should run under the security
context of the user calling the function. This is the default.
SELF indicates that the UDF should run under the security
context of the user who created (or altered) the function.
OWNER indicates that the UDF should run under the security

context of the owner of the UDF (or the


owner of the schema containing the UDF).
Finally, you can specify that the UDF
should run under the security context of a
specific user by specifying a username.

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.

Listado 4-1. Simple escalar UDF


CREAR dbo.CalculateCircleArea FUNCIN (Radius float = 1,0) VUELVE flotador
CON devuelve NULL ON NULL INPUT AS
COMENZAR
RETURN PI () * POWER (Radius, 2); FIN;
La primera lnea de la sentencia CREATE FUNCTION define el esquema y el nombre de la funcin
utilizando un nombre de SQL Server estndar de dos partes (dbo.CalculateCircleArea) y un nico
parmetro obligatorio, el radio del crculo (Radius). El parmetroRadius se define como un tipo de
flotador de T-SQL. El parmetro se le asigna un valor por defecto de 1.0 por los = 1.0 despus de la
declaracin de parmetros:
CREAR dbo.CalculateCircleArea FUNCIN (Radius float = 1,0)
La siguiente lnea contiene la palabra clave DEVOLUCIONES, que especifica el tipo de datos del
resultado que ser devuelta por la UDF. En este caso, la palabra clave DEVOLUCIONES indica que la
UDF devolver un resultado float:
DEVOLUCIONES flotan
La tercera lnea contiene opciones adicionales siguientes la palabra clave CON. El ejemplo utiliza los
RETURNS NULL opcin de la funcin NULL INPUT para una mejora del rendimiento en ON. Los
RETURNS NULL opcin NULL INPUT es una opcin Mejora la performance que devuelve
automticamente NULL si alguno de los parmetros pasados en son NULL. La mejora del rendimiento se
produce porque SQL Server no se ejecutar el cuerpo de la funcin si un NULL se pasa y se especifica
esta opcin:
CON devuelve NULL ON NULL INPUT
La palabra clave AS indica el comienzo del cuerpo de la funcin que debe ser encerrado en el T-SQL
BEGIN y END palabras clave. La funcin de ejemplo en el Listado 4-1 es muy simple, que consiste en
una sola sentencia RETURN que devuelve inmediatamente el valor del clculo del rea del crculo. La
sentencia RETURN debe ser la ltima declaracin ante la palabra clave END en cada UDF escalar:
RETURN PI () * POWER (radius, 2);
Usted puede probar este sencillo UDF con algunas sentencias SELECT como la siguiente. Los resultados
se muestran en la Figura 4-1:
SELECT dbo.CalculateCircleArea (10); SELECT dbo.CalculateCircleArea (NULL); SELECT
dbo.CalculateCircleArea (2.5);

Figura 4-1. Los resultados de los clculos de rea de la muestra de crculo


PARMETROS UDF
Parmetros de UDF operan de manera similar a, pero ligeramente diferente, de procedimiento
almacenado parmetros (SP). Es importante ser consciente de las diferencias. Por ejemplo, si crea una
UDF que no acepta parmetros, usted todava tiene que incluir parntesis vacos despus de la funcin
nombre-tanto en la creacin y al invocar la funcin. Algunas funciones incorporadas, como la funcin PI
() utilizado en el listado 1.4, que representa la
valor de la constante (3.14159265358979), no toma parmetros. Observe que cuando la funcin se
llama en el UDF, todava llamado con parntesis vacos.
Cuando los SP se asignan los valores por defecto, puede simplemente dejar el parmetro fuera de su lista
de parmetros completamente al llamar al procedimiento. Esto no es una opcin con UDF. Para utilizar un
valor por defecto UDF, debe utilizar la palabra clave DEFAULT al llamar la UDF. Para utilizar el valor
por defecto para el parmetroradius del ejemplo

dbo.CalculateCircleArea UDF, que llame a la UDF como esto:


SELECT dbo.CalculateCircleArea (DEFAULT);
Por ltimo, los SP no tienen equivalente a los RETURNS NULL opcin NULL INPUT. Puede simular
esta funcionalidad en cierta medida por el control de sus parmetros para NULL inmediatamente al entrar
en el SP, sin embargo. SP se discuten en mayor detalle en el captulo 5.
UDF proporcionan varias opciones de tiempo de creacin que te permitirn mejorar el rendimiento y la
seguridad, incluyendo las siguientes:
La opcin de cifrado se puede utilizar para almacenar su UDF en la base de datos en formato ofuscado.
Tenga en cuenta que esto no es cierto cifrado, sino ms bien una ofuscacin fcilmente burlado de su
cdigo. Vea el "UDF
'Cifrado' "barra lateral para obtener ms informacin.
La opcin SCHEMABINDING indica que su UDF estar obligado a objetos de base de referencia en el
cuerpo de la funcin. Con SCHEMABINDING encendido, los intentos de cambiar o eliminar tablas
referenciada y otros objetos de base de datos como resultado de un error. Esto ayuda a prevenir cambios
accidentales de mesas y otros objetos de base de datos que pueden romper su UDF. Adems, el equipo de
SQL Server Database Engine ha publicado informacin que indica que SCHEMABINDING puede
mejorar el rendimiento de las UDF, incluso si no hacen referencia a otros objetos de base de datos
(http://blogs.msdn.com/b/sqlprogrammability/archive/2
El LLAMADO opcin NULL INPUT es lo contrario de RETURNS NULL ON NULL INPUT. Cuando
LLAMADO EN se especifica NULL INPUT, SQL Server ejecuta el cuerpo de la funcin, incluso si uno o
ms parmetros son NULL. LLAMADO ON NULL INPUT es una opcin por defecto para todas las
funciones con valores escalares.
El EXECUTE AS opcin administra la seguridad de llamadas en las UDF. Puede especificar que la UDF
se ejecutar como cualquiera de los siguientes:
LLAMADAS indica que la UDF debe ejecutarse bajo el contexto de seguridad del usuario llama a la
funcin. Este es el valor predeterminado.
AUTO indica que la UDF debe ejecutarse bajo el contexto de seguridad del usuario que ha creado (o
alterada) la funcin.
PROPIETARIO indica que la UDF debe ejecutarse bajo la seguridad
contexto de la duea de la UDF (o el propietario del esquema que contiene la UDF).
Por ltimo, se puede especificar que la UDF debe ejecutarse bajo el contexto de seguridad de un usuario
especfico especificando un nombre de usuario.
UDF "cifrado"
El uso de la opcin de cifrado en las UDF realiza una sencilla ofuscacin de su cdigo. En realidad, no
hace ms que "mantener a la gente honesta", y en realidad tiende a ser ms problemtico de lo que vale.
Muchos desarrolladores y administradores de bases han pasado un tiempo precioso recorriendo la Internet
para disfrutar de herramientas para descifrar sus objetos de base de datos, ya que estaban convencidos de
los scripts en su base de datos de control de cdigo fuente estaban fuera de sincronizacin con la base de
datos de produccin. Tenga en cuenta que esas mismas herramientas de descifrado estn disponibles para
cualquier persona con una conexin a Internet y un navegador. Si usted escribe guiones de bases de datos
comerciales o realiza servicios de consultora de la base de datos, su mejor (y en realidad slo) la
proteccin contra los administradores de bases curiosos y desarrolladores de ingeniera inversa y la
modificacin de su cdigo es un contrato bien escrito. Tenga esto en cuenta a la hora de decidir si "cifrar"
sus objetos de base de datos.

Das könnte Ihnen auch gefallen