Compartir a través de


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

Actualización: noviembre 2007

Cree un tipo de SQL definido por el usuario agregando un Tipo definido por el usuario a un proyecto SQL Server. Después de la implementación correcta, puede usarlo en todos los contextos en los que use un tipo de sistema. Esto incluye definiciones de columna, variables, parámetros, resultados de función, cursores, desencadenadores y replicación. Los tipos definidos por el usuario proporcionan extensibilidad del usuario del sistema de tipo de datos del servidor SQL, además de capacidad para definir tipos estructurados complejos.

Nota:

De forma predeterminada, la característica de integración de Common Language Runtime (CLR) está desactivada 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:

Es posible que su equipo muestre nombres o ubicaciones diferentes para algunos de los elementos de la interfaz de usuario de Visual Studio incluidos en las instrucciones siguientes. La edición de Visual Studio que se tenga y la configuración que se utilice determinan estos elementos. Para obtener más información, vea Valores de configuración de Visual Studio.

Creación de un tipo definido por el usuario

Para crear un tipo definido por el usuario de SQL

  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, seleccione Agregar nuevo elemento.

  3. Seleccione Tipo definido por el usuario en Agregar nuevo elemento (Cuadro de diálogo).

  4. Escriba un Nombre para el nuevo tipo definido por el usuario.

  5. Agregue el código para definir y crear el tipo definido por el usuario. Vea el primer ejemplo incluido después de este procedimiento.

    Nota:

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

  6. Para Visual Basic y Visual C#, en el Explorador de soluciones, abra la carpeta SecuenciasDePrueba y haga doble clic en el archivo Test.sql.

    Para Visual C++, en el Explorador de soluciones, haga doble clic en el archivo debug.sql.

  7. Agregue código al archivo Test.sql (debug.sql en Visual C++) para ejecutar el tipo definido por el usuario. Vea el segundo ejemplo incluido después de este procedimiento.

  8. Presione F5 para generar, implementar y depurar el tipo definido por el usuario. Para obtener información sobre cómo implementar sin depurar, vea Cómo: Implementar elementos de proyecto de SQL Server en un servidor SQL Server.

  9. Vea los resultados que se muestran en la Resultados (Ventana) y seleccione Mostrar resultados desde: Resultado de base de datos.

Ejemplo

Este ejemplo crea un tipo Point que puede utilizar de la misma forma que los otros tipos simples. La declaración de clase es representativa con Serializable y los atributos SqlUserDefinedTypeAttribute. La propiedad Format de SqlUserDefinedTypeAttribute determina el formato de almacenamiento del tipo definido por el usuario. El tipo implementa la conversión de cadenas mediante la implementación de los métodos Parse y ToString. El tipo también implementa dos procedimientos de propiedad para obtener y establecer los valores de X e Y para el punto representado por esta clase.

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

<Serializable()> _
<SqlUserDefinedType(Format.Native)> _
Public Structure Point
    Implements INullable

    Private m_x As Int32
    Private m_y As Int32
    Private is_Null As Boolean


    Public Property X() As Int32
        Get
            Return (Me.m_x)
        End Get
        Set(ByVal Value As Int32)
            m_x = Value
        End Set
    End Property


    Public Property Y() As Int32
        Get
            Return (Me.m_y)
        End Get
        Set(ByVal Value As Int32)
            m_y = Value
        End Set
    End Property


    Public ReadOnly Property IsNull() As Boolean Implements INullable.IsNull
        Get
            Return is_Null
        End Get
    End Property


    Public Shared ReadOnly Property Null() As Point
        Get
            Dim pt As Point = New Point
            pt.is_Null = True
            Return pt
        End Get
    End Property


    Public Overrides Function ToString() As String
        If Me.IsNull() Then
            Return Nothing
        Else
            Return Me.m_x & ":" & Me.m_y
        End If
    End Function


    Public Shared Function Parse(ByVal s As SqlString) As Point
        If s = SqlString.Null Then
            Return Null
        End If

        If s.ToString() = SqlString.Null.ToString() Then
            Return Null
        End If

        If s.IsNull Then
            Return Null
        End If

        'Parse input string here to separate out coordinates
        Dim str As String = Convert.ToString(s)
        Dim xy() As String = str.Split(":"c)

        Dim pt As New Point()
        pt.X = CType(xy(0), Int32)
        pt.Y = CType(xy(1), Int32)
        Return (pt)
    End Function


    Public Function Quadrant() As SqlString

        If m_x = 0 And m_y = 0 Then
            Return "centered"
        End If

        Dim stringResult As String = ""

        Select Case m_x
            Case 0
                stringResult = "center"
            Case Is > 0
                stringResult = "right"
            Case Is < 0
                stringResult = "left"
        End Select

        Select Case m_y
            Case 0
                stringResult = stringResult & " center"
            Case Is > 0
                stringResult = stringResult & " top"
            Case Is < 0
                stringResult = stringResult & " bottom"
        End Select

        Return stringResult
    End Function
End Structure
using System;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;

[Serializable()]
[SqlUserDefinedType(Format.Native)]
public struct Point : INullable
{
    private Int32 m_x;
    private Int32 m_y;
    private bool is_Null;


    public Int32 X
    {
        get
        {
            return (this.m_x);
        }
        set
        {
            m_x = value;
        }
    }


    public Int32 Y
    {
        get
        {
            return (this.m_y);
        }
        set
        {
            m_y = value;
        }
    }


    public bool IsNull
    {
        get
        {
            return is_Null;
        }
    }


    public static Point Null
    {
        get
        {
            Point pt = new Point();
            pt.is_Null = true;
            return (pt);
        }
    }


    public override string ToString()
    {
        if (this.IsNull)
        {
            return "NULL";
        }
        else
        {
            return this.m_x + ":" + this.m_y;
        }
    }


    public static Point Parse(SqlString s)
    {
        if (s.IsNull)
        {
            return Null;
        }

        // Parse input string here to separate out coordinates
        string str = Convert.ToString(s);
        string[] xy = str.Split(':');

        Point pt = new Point();
        pt.X = Convert.ToInt32(xy[0]);
        pt.Y = Convert.ToInt32(xy[1]);
        return (pt);
    }


    public SqlString Quadrant()
    {
        if (m_x == 0 && m_y == 0)
        {
            return "centered";
        } 

        SqlString stringReturn = "";

        if (m_x == 0)
        {
            stringReturn = "center";
        }
        else if (m_x > 0)
        {
            stringReturn = "right";
        } 
        else if (m_x < 0)
        {
            stringReturn = "left";
        }

        if (m_y == 0) 
        {
            stringReturn = stringReturn + " center";
        }
        else if (m_y > 0)
        {
            stringReturn = stringReturn + " top";
        }
        else if (m_y < 0)
        {
            stringReturn = stringReturn + " bottom";
        }

        return stringReturn;
    }
}
#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 User-Defined Types, add the following to your debug.sql file:
//
// CREATE TABLE test_table (column1 Point)
//
// INSERT INTO test_table (column1) VALUES ('1:2')
// INSERT INTO test_table (column1) VALUES ('-2:3')
// INSERT INTO test_table (column1) VALUES ('-3:-4')
//
// SELECT column1.Quadrant() FROM test_table
//
// DROP TABLE test_table
//
[Serializable]
[SqlUserDefinedType(Format::Native)]
public value struct Point : public INullable
{
private:
    Int32 m_x;
    Int32 m_y;
    bool is_Null;

public:
    property Int32 X
    {
        Int32 get() { return (this->m_x); }
        void set(Int32 value) { m_x = value; }
    }

    property Int32 Y
    {
        Int32 get() { return (this->m_y); }
        void set(Int32 value) { m_y = value; }
    }

    virtual property bool IsNull
    {
        bool get() { return is_Null; }
    }

    static property Point Null
    {
        Point get()
        {
            Point pt;
            pt.is_Null = true;
            return (pt);
        }
    }

    virtual String ^ToString() override
    {
        if (this->IsNull)
        {
            return "NULL";
        }
        else
        {
            return this->m_x + ":" + this->m_y;
        }
    }


    static Point Parse(SqlString s)
    {
        if (s.IsNull)
        {
            return Null;
        }

        // Parse input string here to separate out coordinates
        String ^str = Convert::ToString(s);
        array<String ^> ^xy = str->Split(':');

        Point pt;
        pt.X = Convert::ToInt32(xy[0]);
        pt.Y = Convert::ToInt32(xy[1]);
        return (pt);
    }


    SqlString Quadrant()
    {
        if (m_x == 0 && m_y == 0)
        {
            return "centered";
        }

        SqlString stringReturn = "";

        if (m_x == 0)
        {
            stringReturn = "center";
        }
        else if (m_x > 0)
        {
            stringReturn = "right";
        }
        else if (m_x < 0)
        {
            stringReturn = "left";
        }

        if (m_y == 0)
        {
            stringReturn = stringReturn + SqlString(" center");
        }
        else if (m_y > 0)
        {
            stringReturn = stringReturn + SqlString(" top");
        }
        else if (m_y < 0)
        {
            stringReturn = stringReturn + SqlString(" bottom");
        }

        return stringReturn;
    }
};

Agregue el código para ejecutar y probar el tipo definido por el usuario (Point) en el archivo Test.sql (debug.sql en Visual C++) de la carpeta SecuenciasDePrueba del proyecto. Por ejemplo, para comprobar el nuevo tipo, cree una tabla que utilice este tipo. El siguiente ejemplo muestra cómo utilizar el tipo Point en la creación de la tabla.

CREATE TABLE test_table (column1 Point)
go

INSERT INTO test_table (column1) VALUES ('1:2')
INSERT INTO test_table (column1) VALUES ('-2:3')
INSERT INTO test_table (column1) VALUES ('-3:-4')

select column1.Quadrant() from test_table

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