利用 CommandStream 屬性執行範本檔案

這個範例說明如何使用 SqlXmlCommand 物件的 CommandStream 屬性來指定由 SQL 或 XPath 查詢所組成的範例檔案。在此應用程式中會針對命令檔案開啟 FileStream物件,而檔案資料流則會指派為執行的 CommandStream

在下列範例中,CommandType 屬性會指定為 SqlXmlCommandType.Template (而非 TemplateFile)。

這是 XML 範本範例:

<ROOT xmlns:sql="urn:schemas-microsoft-com:xml-sql">
  <sql:query>
    SELECT TOP 2 ContactID, FirstName, LastName 
    FROM   Person.Contact
    FOR XML AUTO
  </sql:query>
</ROOT>

這是 C# 應用程式範例。若要測試應用程式,請儲存範本 (TemplateFile.xml),然後再執行應用程式。應用程式會執行在 XML 範本中指定的查詢,並將產生的 XML 文件顯示在螢幕上。

[!附註]

在程式碼中,您必須於連接字串內提供 Microsoft SQL Server 執行個體的名稱。

using System;
using Microsoft.Data.SqlXml;
using System.IO;

class Test
{
      static string ConnString = "Provider=SQLOLEDB;Server=(local);database=AdventureWorks;Integrated Security=SSPI";
      public static int testParams()
      {
         //Stream strm;
         MemoryStream ms = new MemoryStream();
         StreamWriter sw = new StreamWriter(ms);
         ms.Position = 0;
         SqlXmlCommand cmd = new SqlXmlCommand(ConnString);
         cmd.CommandStream = new FileStream("TemplateFile.xml", FileMode.Open, FileAccess.Read);
         cmd.CommandType = SqlXmlCommandType.Template;
         using (Stream strm = cmd.ExecuteStream())
         {
            using (StreamReader sr = new StreamReader(strm)){
               Console.WriteLine(sr.ReadToEnd());
            }
         }
         return 0;      
      }

      public static int Main(String[] args)
      {
         testParams();   
         return 0;
      }
   }

若要測試此範例,您必須先在電腦上安裝 Microsoft .NET Framework。

若要測試應用程式

  1. 將這個範例所提供的 XML 範本 (TemplateFile.xml) 儲存在資料夾中。

  2. 將此範例中提供的 C# 程式碼 (DocSample.cs) 儲存到與結構描述相同的資料夾中 (如果您將檔案儲存在不同的資料夾中,您將需要編輯程式碼,然後為對應的結構描述指定適當的目錄路徑)。

  3. 編譯程式碼。若要在命令提示字元中編譯程式碼,請使用:

    csc /reference:Microsoft.Data.SqlXML.dll DocSample.cs
    

    這樣會建立一個可執行檔 (DocSample.exe)。

  4. 在命令提示字元中執行 DocSample.exe。