Pobieranie danych UDT
W celu utworzenia typ zdefiniowany przez użytkownika (UDT) na komputerze klienckim, wirtualny plik dziennika, został zarejestrowany jako UDT w SQL Server Baza danych musi być dostępna dla aplikacji klient. UDT wirtualny plik dziennika mogą być umieszczane w tym samym katalogu, w aplikacji lub w globalnej wirtualny plik dziennika buforze (GAC).Można również ustawić odwołanie do wirtualny plik dziennika w projekcie.
Wymagania dotyczące użycia UDTs w ADO.NET
wirtualny plik dziennika Załadowania SQL Server oraz wirtualny plik dziennika na komputerze klienckim musi być zgodny w celu UDT ma zostać utworzony na komputerze klienckim. Dla UDTs zdefiniowane przy użyciu Native format serializacji zestawów muszą być zgodne strukturalnie. Dla zestawów zdefiniowane przy użyciu UserDefined Format, zespół musi być dostępny na klient.
Aby pobrać dane z kolumna UDT w tabela nie ma potrzeby kopię wirtualny plik dziennika UDT na komputerze klienckim.
Uwaga
Klient SQL może nie załadować UDT w przypadku wystąpienia niezgodnej wersji UDT lub innych problemów.W takim przypadek do ustalenia, dlaczego nie można odnaleźć wirtualny plik dziennika, zawierającego UDT przez wywołania aplikacji za pomocą regularnie mechanizmów rozwiązywania problemów.Aby uzyskać więcej informacji obejrzeć „ rozpoznawanie błędów z zarządzanych debugowania Asystentów"w programie .NET Framework.
Uzyskiwanie dostępu do UDTs z SqlDataReader
A System.Data.SqlClient.SqlDataReader można używać z kodu klient pobrać zestaw wyników zawierający kolumna UDT, który jest dostępny jako wystąpienie obiektu.
Przykład
W tym przykładzie przedstawiono sposób użycia Main metoda w celu utworzenia nowego SqlDataReader obiekt. Przykładowy kod przypada na następujących czynności:
Tworzy nową metoda Main SqlDataReader obiekt i pobiera wartości z tabela punkty, które z nich zawiera kolumna UDT o nazwie punktu.
Punkt UDT udostępnia współrzędne X i Y zdefiniowane jako liczby całkowite.
UDT określa Distance Metoda oraz GetDistanceFromXY Metoda.
Przykładowy kod pobiera wartości klucz podstawowy i UDT kolumn w celu pokazania możliwości UDT.
Wywołania kod przykładowy Point.Distance i Point.GetDistanceFromXY metody.
Wyniki są wyświetlane w oknie konsoli.
Uwaga
Aplikacja musi być już odwołanie do wirtualny plik dziennika UDT.
Option Explicit On
Option Strict On
Imports System
Imports System.Data.Sql
Imports System.Data.SqlClient
Module ReadPoints
Sub Main()
Dim connectionString As String = GetConnectionString()
Using cnn As New SqlConnection(connectionString)
cnn.Open()
Dim cmd As New SqlCommand( _
"SELECT ID, Pnt FROM dbo.Points", cnn)
Dim rdr As SqlDataReader
rdr = cmd.ExecuteReader
While rdr.Read()
' Retrieve the value of the Primary Key column
Dim id As Int32 = rdr.GetInt32(0)
' Retrieve the value of the UDT
Dim pnt As Point = CType(rdr(1), Point)
' You can also use GetSqlValue and GetValue
' Dim pnt As Point = CType(rdr.GetSqlValue(1), Point)
' Dim pnt As Point = CType(rdr.GetValue(1), Point)
' Print values
Console.WriteLine( _
"ID={0} Point={1} X={2} Y={3} DistanceFromXY={4} Distance={5}", _
id, pnt, pnt.X, pnt.Y, pnt.DistanceFromXY(1, 9), pnt.Distance())
End While
rdr.Close()
Console.WriteLine("done")
End Using
End Sub
Private Function GetConnectionString() As String
' To avoid storing the connection string in your code,
' you can retrieve it from a configuration file.
Return "Data Source=(local);Initial Catalog=AdventureWorks;" _
& "Integrated Security=SSPI;"
End Function
End Module
using System;
using System.Data.Sql;
using System.Data.SqlClient;
namespace Microsoft.Samples.SqlServer
{
class ReadPoints
{
static void Main()
{
string connectionString = GetConnectionString();
using (SqlConnection cnn = new SqlConnection(connectionString))
{
cnn.Open();
SqlCommand cmd = new SqlCommand(
"SELECT ID, Pnt FROM dbo.Points", cnn);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
// Retrieve the value of the Primary Key column
int id = rdr.GetInt32(0);
// Retrieve the value of the UDT
Point pnt = (Point)rdr[1];
// You can also use GetSqlValue and GetValue
// Point pnt = (Point)rdr.GetSqlValue(1);
// Point pnt = (Point)rdr.GetValue(1);
Console.WriteLine(
"ID={0} Point={1} X={2} Y={3} DistanceFromXY={4} Distance={5}",
id, pnt, pnt.X, pnt.Y, pnt.DistanceFromXY(1, 9), pnt.Distance());
}
rdr.Close();
Console.WriteLine("done");
}
static private string GetConnectionString()
{
// To avoid storing the connection string in your code,
// you can retrieve it from a configuration file.
return "Data Source=(local);Initial Catalog=AdventureWorks;"
+ "Integrated Security=SSPI";
}
}
wiązanie UDTs jako liczba bajtów
W niektórych sytuacjach można pobierać dane z kolumna UDT.Być może typ nie jest dostępny lokalnie lub nie chcesz, aby utworzyć wystąpienie UDT.Nieprzetworzony bajtów można znaleźć w tablicy bajtów przy użyciu GetBytes Metoda SqlDataReader. Ta metoda odczytuje strumienia bajtów z przesunięcie w określonej kolumnie do buforu, począwszy od przesunięcie buforu w określonej tablicy.Inną możliwością jest jeden z GetSqlBytes or GetSqlBinary metod i odczytywania całej zawartości w jednej operacji.W obu przypadkach obiektu UDT nigdy nie zostanie uruchomiony, dzięki czemu nie trzeba ustawić odwołanie do UDT wirtualny plik dziennika klient.
Przykład
W tym przykładzie pokazano, jak pobrać Punkt dane raw bajtów w tablicy bajtów, przy użyciu SqlDataReader. Wykorzystuje kod System.Text.StringBuilder Aby konwertować surowe bajtów na ciąg znaków reprezentujący mają być wyświetlane w oknie konsoli.
Option Explicit On
Option Strict On
Imports System
Imports System.Data.Sql
Imports System.Data.SqlClient
Imports System.Data.SqlTypes
Imports System.Text
Module GetRawBytes
Sub Main()
Dim connectionString As String = GetConnectionString()
Using cnn As New SqlConnection(connectionString)
cnn.Open()
Dim cmd As New SqlCommand( _
"SELECT ID, Pnt FROM dbo.Points", cnn)
Dim rdr As SqlDataReader
rdr = cmd.ExecuteReader
While rdr.Read()
' Retrieve the value of the Primary Key column
Dim id As Int32 = rdr.GetInt32(0)
' Retrieve the raw bytes into a byte array
Dim buffer(31) As Byte
Dim byteCount As Integer = _
CInt(rdr.GetBytes(1, 0, buffer, 0, 31))
' Format and print bytes
Dim str As New StringBuilder
str.AppendFormat("ID={0} Point=", id)
Dim i As Integer
For i = 0 To (byteCount - 1)
str.AppendFormat("{0:x}", buffer(i))
Next
Console.WriteLine(str.ToString)
End While
rdr.Close()
Console.WriteLine("done")
End Using
End Sub
Private Function GetConnectionString() As String
' To avoid storing the connection string in your code,
' you can retrieve it from a configuration file.
Return "Data Source=(local);Initial Catalog=AdventureWorks;" _
& "Integrated Security=SSPI;"
End Function
End Module
using System;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Text;
class GetRawBytes
{
static void Main()
{
string connectionString = GetConnectionString();
using (SqlConnection cnn = new SqlConnection(connectionString))
{
cnn.Open();
SqlCommand cmd = new SqlCommand("SELECT ID, Pnt FROM dbo.Points", cnn);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
// Retrieve the value of the Primary Key column
int id = rdr.GetInt32(0);
// Retrieve the raw bytes into a byte array
byte[] buffer = new byte[32];
long byteCount = rdr.GetBytes(1, 0, buffer, 0, 32);
// Format and print bytes
StringBuilder str = new StringBuilder();
str.AppendFormat("ID={0} Point=", id);
for (int i = 0; i < byteCount; i++)
str.AppendFormat("{0:x}", buffer[i]);
Console.WriteLine(str.ToString());
}
rdr.Close();
Console.WriteLine("done");
}
static private string GetConnectionString()
{
// To avoid storing the connection string in your code,
// you can retrieve it from a configuration file.
return "Data Source=(local);Initial Catalog=AdventureWorks;"
+ "Integrated Security=SSPI";
}
}
}
Przykład za pomocą GetSqlBytes
W tym przykładzie pokazano, jak pobrać Punkt dane raw bajtów w jednej operacji przy użyciu GetSqlBytes metoda.Wykorzystuje kod StringBuilder Aby konwertować surowe bajtów na ciąg znaków reprezentujący mają być wyświetlane w oknie konsoli.
Option Explicit On
Option Strict On
Imports System
Imports System.Data.Sql
Imports System.Data.SqlClient
Imports System.Data.SqlTypes
Imports System.Text
Module GetRawBytes
Sub Main()
Dim connectionString As String = GetConnectionString()
Using cnn As New SqlConnection(connectionString)
cnn.Open()
Dim cmd As New SqlCommand( _
"SELECT ID, Pnt FROM dbo.Points", cnn)
Dim rdr As SqlDataReader
rdr = cmd.ExecuteReader
While rdr.Read()
' Retrieve the value of the Primary Key column
Dim id As Int32 = rdr.GetInt32(0)
' Use SqlBytes to retrieve raw bytes
Dim sb As SqlBytes = rdr.GetSqlBytes(1)
Dim byteCount As Long = sb.Length
' Format and print bytes
Dim str As New StringBuilder
str.AppendFormat("ID={0} Point=", id)
Dim i As Integer
For i = 0 To (byteCount - 1)
str.AppendFormat("{0:x}", sb(i))
Next
Console.WriteLine(str.ToString)
End While
rdr.Close()
Console.WriteLine("done")
End Using
End Sub
Private Function GetConnectionString() As String
' To avoid storing the connection string in your code,
' you can retrieve it from a configuration file.
Return "Data Source=(local);Initial Catalog=AdventureWorks;" _
& "Integrated Security=SSPI;"
End Function
End Module
using System;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Text;
class GetRawBytes
{
static void Main()
{
string connectionString = GetConnectionString();
using (SqlConnection cnn = new SqlConnection(connectionString))
{
cnn.Open();
SqlCommand cmd = new SqlCommand(
"SELECT ID, Pnt FROM dbo.Points", cnn);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
// Retrieve the value of the Primary Key column
int id = rdr.GetInt32(0);
// Use SqlBytes to retrieve raw bytes
SqlBytes sb = rdr.GetSqlBytes(1);
long byteCount = sb.Length;
// Format and print bytes
StringBuilder str = new StringBuilder();
str.AppendFormat("ID={0} Point=", id);
for (int i = 0; i < byteCount; i++)
str.AppendFormat("{0:x}", sb[i]);
Console.WriteLine(str.ToString());
}
rdr.Close();
Console.WriteLine("done");
}
static private string GetConnectionString()
{
// To avoid storing the connection string in your code,
// you can retrieve it from a configuration file.
return "Data Source=(local);Initial Catalog=AdventureWorks;"
+ "Integrated Security=SSPI";
}
}
}
Praca z Parametry UDT
UDTs może być używane jako parametry wejściowe i wyjściowe w kodzie ADO.NET.
Za pomocą UDTs w parametry kwerendy
UDTs mogą być używane jako wartości parametru, podczas konfigurowania SqlParameter Aby System.Data.SqlClient.SqlCommand obiekt. The SqlDbType.Udt enumeration of a SqlParameter object is used to indicate that the parameter is a UDT when calling the Add metoda to the Parameters kolekcja. The UdtTypeName właściwość of a SqlCommand object is used to specify the fully qualified name of the UDT in the database using the database.schema_name.object_name syntax.Chociaż nie jest wymagane, przy użyciu w pełni kwalifikowanej nazwy usuwa niejednoznaczności z kodu.
Uwaga
Lokalną kopię wirtualny plik dziennika UDT muszą być dostępne w projekcie klient.
Przykład
Tworzy kod w tym przykładzie SqlCommand i SqlParameter obiekty, aby wstawić dane do kolumna UDT w tabela. W kodzie wykorzystano SqlDbType.Udt Wyliczanie, aby określić typ danych oraz UdtTypeName Właściwość SqlParameter obiekt do określenia w pełni kwalifikowanej nazwy UDT w bazie danych.
Option Explicit On
Option Strict On
Imports System
Imports system.Data
Imports System.Data.Sql
Imports System.Data.SqlClient
Module Module1
Sub Main()
Dim ConnectionString As String = GetConnectionString()
Dim cnn As New SqlConnection(ConnectionString)
Using cnn
Dim cmd As SqlCommand = cnn.CreateCommand()
cmd.CommandText = "INSERT INTO dbo.Points (Pnt) VALUES (@Point)"
cmd.CommandType = CommandType.Text
Dim param As New SqlParameter("@Point", SqlDbType.Udt) param.UdtTypeName = "TestPoint.dbo.Point" param.Direction = ParameterDirection.Input param.Value = New Point(5, 6) cmd.Parameters.Add(param)
cnn.Open()
cmd.ExecuteNonQuery()
Console.WriteLine("done")
End Using
End Sub
Private Function GetConnectionString() As String
' To avoid storing the connection string in your code,
' you can retrieve it from a configuration file.
Return "Data Source=(local);Initial Catalog=AdventureWorks;" _
& "Integrated Security=SSPI;"
End Function
End Module
using System;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
class Class1
{
static void Main()
{
string ConnectionString = GetConnectionString();
using (SqlConnection cnn = new SqlConnection(ConnectionString))
{
SqlCommand cmd = cnn.CreateCommand();
cmd.CommandText =
"INSERT INTO dbo.Points (Pnt) VALUES (@Point)";
cmd.CommandType = CommandType.Text;
SqlParameter param = new SqlParameter("@Point", SqlDbType.Udt); param.UdtTypeName = "TestPoint.dbo.Point"; param.Direction = ParameterDirection.Input; param.Value = new Point(5, 6); cmd.Parameters.Add(param);
cnn.Open();
cmd.ExecuteNonQuery();
Console.WriteLine("done");
}
static private string GetConnectionString()
{
// To avoid storing the connection string in your code,
// you can retrieve it from a configuration file.
return "Data Source=(local);Initial Catalog=AdventureWorks;"
+ "Integrated Security=SSPI";
}
}
}