Share via


Cómo: Crear y ejecutar un agregado CLR de SQL Server

Actualización: noviembre 2007

Cree agregados de SQL agregando elementos Agregado a los proyectos de SQL Server. Después de una correcta implementación, se llaman a los agregados creados en código administrado y se ejecutan como cualquier otro agregado de SQL Server.

Nota:

La característica de integración Common Language Runtime (CLR) está desactivada de forma predeterminada en Microsoft SQL Server y se debe habilitar con el fin de utilizar los elementos de los proyectos de SQL Server. Para habilitar la integración CLR, utilice la opción clr enabled del procedimiento almacenado sp_configure. Para obtener más información, vea Habilitación de la integración CLR.

Nota:

Los agregados de SQL Server requieren que se implementen cuatros métodos específicos: Init, Accumulate, Merge y Terminate. Para obtener más información, vea el tema Funciones de agregados definidos por el usuario de SQL CLR .NET en SQL Books Online.

Nota:

Los cuadros de diálogo y comandos de menú que se ven pueden diferir de los descritos en la Ayuda, en función de los valores de configuración o de edición activos. Para cambiar la configuración, elija la opción Importar y exportar configuraciones del menú Herramientas. Para obtener más información, vea Valores de configuración de Visual Studio.

Crear un agregado de SQL Server

Para crear un agregado de SQL Server

  1. Abra un Proyecto de SQL Server existente o cree uno nuevo. Para obtener más información, vea Cómo: Crear un proyecto de SQL Server.

  2. En el menú Proyecto, elija Agregar nuevo elemento.

  3. Seleccione Agregado en Agregar nuevo elemento (Cuadro de diálogo).

  4. Escriba un Nombre para el nuevo agregado.

  5. Agregue el código que se va a ejecutar cuando se ejecuta el agregado. Vea el primer ejemplo siguiente.

Nota:

Los ejemplos en C++ se deben compilar con la opción /clr:safe del compilador.

  1. Implemente el agregado en un SQL Server. Para obtener más información, vea Cómo: Implementar elementos de proyecto de SQL Server en un servidor SQL Server.

  2. Depure al agregado ejecutándolo en SQL Server. Vea el segundo ejemplo siguiente.

Ejemplo

Este ejemplo crea un agregado para contar la vocales de una columna de los tipos de datos de una cadena. El agregado contiene los cuatros métodos necesarios siguientes, que pueden ejecutarse en multiproceso: Init, Accumulate, Merge y Terminate.

Imports System
Imports System.Data.SqlTypes
Imports Microsoft.SqlServer.Server

<Serializable()> _
<SqlUserDefinedAggregate(Format.Native)> _
Public Structure CountVowels

    ' count only the vowels in the passed-in strings
    Private countOfVowels As SqlInt32


    Public Sub Init()
        countOfVowels = 0
    End Sub


    Public Sub Accumulate(ByVal value As SqlString)
        Dim stringChar As String
        Dim indexChar As Int32

        ' for each character in the given parameter
        For indexChar = 0 To Len(value.ToString()) - 1

            stringChar = value.ToString().Substring(indexChar, 1)

            If stringChar.ToLower() Like "[aeiou]" Then

                ' it is a vowel, increment the count
                countOfVowels = countOfVowels + 1
            End If
        Next
    End Sub


    Public Sub Merge(ByVal value As CountVowels)

        Accumulate(value.Terminate())
    End Sub


    Public Function Terminate() As SqlString

        Return countOfVowels.ToString()
    End Function
End Structure
using System;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;

[Serializable]
[SqlUserDefinedAggregate(Format.Native)]
public struct CountVowels
{
    // count only the vowels in the passed-in strings
    private SqlInt32 countOfVowels;


    public void Init()
    {
        countOfVowels = 0;
    }


    public void Accumulate(SqlString value)
    {
        // list of vowels to look for
        string vowels = "aeiou";

        // for each character in the given parameter
        for (int i=0; i < value.ToString().Length; i++)
        {
            // for each character in the vowels string
            for (int j=0; j < vowels.Length; j++)
            {
                // convert parameter character to lowercase and compare to vowel
                if (value.Value.Substring(i,1).ToLower() == vowels.Substring(j,1))
                {
                    // it is a vowel, increment the count
                    countOfVowels+=1;
                }
            }
        }
    }


    public void Merge(CountVowels value)
    {
        Accumulate(value.Terminate());
    }


    public SqlString Terminate()
    {
        return countOfVowels.ToString();
    }
}
#include "stdafx.h"

#using <System.dll>
#using <System.Data.dll>
#using <System.Xml.dll>

using namespace System;
using namespace System::Data;
using namespace System::Data::Sql;
using namespace System::Data::SqlTypes;
using namespace Microsoft::SqlServer::Server;

// In order to debug your Aggregate, add the following to your debug.sql file:
//
// SELECT LastName, COUNT(LastName) AS CountOfLastName, dbo.CountVowels(LastName) AS CountOfVowels
// FROM Person.Contact
// GROUP BY LastName
// ORDER BY LastName
//

[Serializable]
[SqlUserDefinedAggregate(Format::Native)]
public value struct CountVowels
{
public:
    void Init()
    {
        countOfVowels = 0;
    }

    void Accumulate(SqlString value)
    {
        // list of vowels to look for
        String ^vowels = "aeiou";

        // for each character in the given parameter
        for (int i=0; i < value.ToString()->Length; i++)
        {
            // for each character in the vowels string
            for (int j=0; j < vowels->Length; j++)
            {
                // convert parameter character to lowercase and compare to vowel
                if (value.Value->Substring(i, 1)->ToLower() == vowels->Substring(j, 1))
                {
                    // it is a vowel, increment the count
                    countOfVowels+=1;
                    break;
                }
            }
        }
    }

    void Merge(CountVowels value)
    {
        Accumulate(value.Terminate());
    }

    SqlTypes::SqlString Terminate()
    {
        return countOfVowels.ToString();
    }

private:
    // count only the vowels in the passed-in strings
    SqlInt32 countOfVowels;
};

Después de implementar el agregado, ejecútelo en SQL Server y compruebe que devuelve los datos correctos. Esta consulta devuelve un conjunto de resultados del recuento vocales para todos los valores de la columna LastNames de la tabla Contact.

SELECT LastName, COUNT(LastName) AS CountOfLastName, dbo.CountVowels(LastName) AS CountOfVowels
FROM Person.Contact
GROUP BY LastName
ORDER BY LastName

Vea también

Tareas

Cómo: Crear un proyecto de SQL Server

Cómo: Crear y ejecutar un procedimiento CLR almacenado de SQL Server

Cómo: Crear y ejecutar un desencadenador CLR de SQL Server

Cómo: Crear y ejecutar un agregado CLR de SQL Server

Cómo: Crear y ejecutar una función CLR de servidor SQL Server definido por el usuario

Cómo: Crear y ejecutar un tipo CLR de servidor SQL Server definido por el usuario

Tutorial: Crear un procedimiento almacenado en código administrado

Cómo: Depurar un procedimiento almacenado de SQL CLR

Conceptos

Introduction to SQL Server CLR Integration (ADO.NET)

Ventajas de utilizar código administrado para crear objetos de base de datos

Plantillas de elementos para proyectos de SQL Server

Referencia

Atributos para proyectos de servidor SQL Server y objetos de base de datos

Otros recursos

Depuración de bases de datos de SQL CLR