次の方法で共有


パラメータとしての XML 値の指定 (ADO.NET)

更新 : November 2007

値が XML 文字列であるパラメータがクエリに必要な場合、開発者はその値を SqlXml のインスタンスを使用して提供することができます。特別な処理は必要ありません。SQL Server 2005 の XML 列は、他のデータ型と同じ方法でパラメータ値を受け入れます。

次のコンソール アプリケーションでは、AdventureWorks データベースに新しいテーブルを作成します。新しいテーブルには、SalesID という名前の列と、SalesInfo という名前の XML 列があります。

34e4kcbw.alert_note(ja-jp,VS.90).gifメモ :

AdventureWorks サンプル データベースは、既定では SQL Server 2005 のインストール時にはインストールされません。SQL Server Setup を実行してインストールします。

この例では、新しいテーブルに行を挿入するために SqlCommand オブジェクトを準備します。保存されたファイルは、SalesInfo 列に必要な XML データを提供します。

この例を実行させるために必要なファイルを作成するには、プロジェクトと同じフォルダ内に新しいテキスト ファイルを作成します。ファイルに MyTestStoreData.xml という名前を付けます。ファイルをメモ帳で開き、次のテキストをコピーし、貼り付けします。

<StoreSurvey xmlns="https://schemas.microsoft.com/sqlserver/2004/07/adventure-works/StoreSurvey">
  <AnnualSales>300000</AnnualSales>
  <AnnualRevenue>30000</AnnualRevenue>
  <BankName>International Bank</BankName>
  <BusinessType>BM</BusinessType>
  <YearOpened>1970</YearOpened>
  <Specialty>Road</Specialty>
  <SquareFeet>7000</SquareFeet>
  <Brands>3</Brands>
  <Internet>T1</Internet>
  <NumberEmployees>2</NumberEmployees>
</StoreSurvey>

[Visual Basic]

Imports System
Imports System.Data.SqlClient
Imports System.Data.SqlTypes
Imports System.Xml

Module Module1
    Sub Main()

        Using connection As SqlConnection = New SqlConnection(GetConnectionString())
        connection.Open()

        ' Create a sample table (dropping first if it already
        ' exists.)
        Dim commandNewTable As String = _
         "IF EXISTS (SELECT * FROM dbo.sysobjects " & _
         "WHERE id = object_id(N'[dbo].[XmlDataTypeSample]') " & _
         "AND OBJECTPROPERTY(id, N'IsUserTable') = 1) " & _
         "DROP TABLE [dbo].[XmlDataTypeSample];" & _
         "CREATE TABLE [dbo].[XmlDataTypeSample]( " & _
         "[SalesID] [int] IDENTITY(1,1) NOT NULL, " & _
         "[SalesInfo] [xml])"

        Dim commandAdd As New _
         SqlCommand(commandNewTable, connection)
        commandAdd.ExecuteNonQuery()

        Dim commandText As String = _
         "INSERT INTO [dbo].[XmlDataTypeSample] " & _
           "([SalesInfo] ) " & _
           "VALUES(@xmlParameter )"

        Dim command As New SqlCommand(commandText, connection)

        ' Read the saved XML document as a 
        ' SqlXml-data typed variable.
        Dim newXml As SqlXml = _
         New SqlXml(New XmlTextReader("MyTestStoreData.xml"))

        ' Supply the SqlXml value for the value of the parameter.
        command.Parameters.AddWithValue("@xmlParameter", newXml)

        Dim result As Integer = command.ExecuteNonQuery()
        Console.WriteLine(result & " row was added.")
        Console.WriteLine("Press Enter to continue.")
        Console.ReadLine()
    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);Integrated Security=SSPI;" & _
          "Initial Catalog=AdventureWorks"
    End Function
End Module

[C#]

using System;
using System.Data;
using System.Data.SqlClient;
using System.Xml;
using System.Data.SqlTypes;

class Class1
{
    static void Main()
    {
        using (SqlConnection connection = new SqlConnection(GetConnectionString()))
       {
        connection.Open();
        //  Create a sample table (dropping first if it already
        //  exists.)

        string commandNewTable = 
            "IF EXISTS (SELECT * FROM dbo.sysobjects " + 
            "WHERE id = " +
                  "object_id(N'[dbo].[XmlDataTypeSample]') " + 
            "AND OBJECTPROPERTY(id, N'IsUserTable') = 1) " + 
            "DROP TABLE [dbo].[XmlDataTypeSample];" + 
            "CREATE TABLE [dbo].[XmlDataTypeSample]( " + 
            "[SalesID] [int] IDENTITY(1,1) NOT NULL, " + 
            "[SalesInfo] [xml])";
        SqlCommand commandAdd = 
                   new SqlCommand(commandNewTable, connection);
        commandAdd.ExecuteNonQuery();
        string commandText = 
            "INSERT INTO [dbo].[XmlDataTypeSample] " + 
            "([SalesInfo] ) " + 
            "VALUES(@xmlParameter )";
        SqlCommand command = 
                  new SqlCommand(commandText, connection);

        //  Read the saved XML document as a 
        //  SqlXml-data typed variable.
        SqlXml newXml = 
            new SqlXml(new XmlTextReader("MyTestStoreData.xml"));
        
        //  Supply the SqlXml value for the value of the parameter.
        command.Parameters.AddWithValue("@xmlParameter", newXml);

        int result = command.ExecuteNonQuery();
        Console.WriteLine(result + " row was added.");
        Console.WriteLine("Press Enter to continue.");
        Console.ReadLine();
    }
  }

    private static string GetConnectionString()
    {
        // To avoid storing the connection string in your code,            
        // you can retrieve it from a configuration file. 
        return "Data Source=(local);Integrated Security=true;" +
        "Initial Catalog=AdventureWorks; ";
    }
}

参照

概念

SQL Server における XML データ (ADO.NET)

参照

SqlXml