共用方式為


利用 CommandStream 屬性執行範本檔案

適用於:SQL ServerAzure SQL 資料庫

此範例說明如何使用 SqlXmlCommand 物件的 CommandStream 屬性來指定包含 SQL 或 XPath 查詢的範本檔案。 在此應用程式中,會針對命令檔案開啟 FileStreamobject,並將檔案數據流指派為執行的 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;  
      }  
   }  

若要測試應用程式

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

  2. 將本範例中提供的 C# 程式代碼 (DocSample.cs) 儲存在儲存架構的相同資料夾中。 (如果您將檔案儲存在不同的資料夾中,則必須編輯程式代碼,並指定對應架構的適當目錄路徑。

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

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

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

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