Compartilhar via


Como: Criar and Run a CLR SQL servidor tipo definido pelo usuário

Criar tipo definido pelo usuário SQL adicionando um User-Defined Type a um projeto SQL Server.Após a implantação bem-sucedida, você pode usá-lo em todos os contextos nos quais você pode usar um tipo de sistema.Isso inclui definições de coluna, variáveis, parâmetros, resultados de funções, cursores, disparadores e replicação.Tipos definidos pelo usuário fornecem extensibilidade do sistema de tipo de dados SQL Server ao usuário e também a capacidade de definir tipos estruturados complexos.

Observação:

Por padrão, o recurso de integração Common Language Runtime (CLR) fica desativado no Microsoft SQL Server e deve ser habilitado para usar itens de projeto SQL Server.Para ativar integração CLR, use o CLR enabled opção de do sp_configure procedimento armazenado.Para obter mais informações, consulte Habilitar integração CLR.

Observação:

Seu computador pode mostrar diferentes nomes ou localizações para alguns dos elementos de interface do usuário do Visual Studio nas instruções a seguir. A edição do Visual Studio que você possui e as configurações que você usa determinam esses elementos. Para obter mais informações, consulte Configurações do Visual Studio.

Criando um tipo definido pelo usuário

Para criar um tipo SQL definido pelo usuário

  1. Abra um existente Projeto do SQL servidor, ou criar um novo.Para obter mais informações, consulte Como: Criar um projeto de SQL servidor.

  2. A partir do menu Project, selecione Add New Item.

  3. Selecione User-Defined Type na Adicionar Novo Item Caixa de diálogo caixa.

  4. Digite um Name para o novo tipo definido pelo usuário.

  5. Adicione um código para definir e criar o tipo definido pelo usuário.Consulte o primeiro exemplo que segue este procedimento.

    Observação:

    Exemplos de C++ devem ser compilados com o / CLR : segurança opção do compilador.

  6. Para Visual Basic e Visual C#, em Solution Explorer, abra a pasta TestScripts e clique duas vezes no arquivo Test.sql.

    Para Visual C++, em Solution Explorer, clique duas vezes no arquivo debug.sql.

  7. Adicione código ao arquivo Test.sql (debug.sql no Visual C++) para executar o tipo definido pelo usuário.Consulte o segundo exemplo que segue este procedimento.

  8. Pressione F5 para criar, implantar e depurar o tipo definido pelo usuário.Para obter informações sobre implantação sem depuração, consulte Como: Implantar o SQL servidor projeto Items em um SQL servidor.

  9. Exibir os resultados que são mostrados no Janela de saída e selecionar Show output from: Banco de dados de saída .

Exemplo

Este exemplo cria um tipo Point que você pode usar como faria com outros tipos simples.A declaração de classe está decorada com ambos os atributos Serializable e SqlUserDefinedTypeAttribute.A propriedade Format de SqlUserDefinedTypeAttribute determina o formato de armazenamento do tipo definido pelo usuário.O tipo implementa conversão da sequência de caracteres através da implementação dos métodos Parse e ToString.O tipo também implementa dois procedimentos de propriedade para obter e definir os valores de X e Y para o ponto representado por esta classe.

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

Adicione um código para executar e testar seu tipo definido pelo usuário (Point)para o arquivo Test.sql (debug.sql no Visual C++) na pasta TestScripts em seu projeto.Por exemplo, para verificar o novo tipo, crie uma tabela que usa esse tipo.O exemplo a seguir demonstra como usar o tipo Point na criação de tabela.

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

Consulte também

Tarefas

Como: Criar um projeto de SQL servidor

Como: Criar e executar um CLR SQL servidor Stored procedimento

Como: Criar e executar um disparar CLR SQL servidor

Como: Criar e executar uma agregação de servidor SQL CLR

Como: Criar and Run a CLR SQL servidor função definida pelo usuário

Como: Criar and Run a CLR SQL servidor tipo definido pelo usuário

Demonstra Passo a passo: Criando um procedimento armazenado em código gerenciado

Como: Depurar um SQL CLR Procedimento Armazenado

Conceitos

Introduction to Integration CLR SQL Servidor

Vantagens de usar código gerenciado para criar objetos de bancos de dados

Modelos de Item para Projetos do SQL Server

Referência

Atributos para projetos SQL Server e objetos de bancos de dados

Outros recursos

Depuração de banco de dados SQL CLR