共用方式為


使用 CommandText 屬性執行範本檔案

適用於:SQL ServerAzure SQL 資料庫

此範例說明如何使用 CommandText 屬性來指定由 SQL 或 XPath 查詢組成的範本檔案。 您可以將檔名指定為 Value,而不是將 SQL 或 XPath 查詢指定為 CommandText 的值。 在下列範例中,CommandType 屬性會指定為 SqlXmlCommandType.TemplateFile。

範例應用程式會執行此範本:

<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),然後執行應用程式。

注意

在程式代碼中,您必須在 連接字串 中提供 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;  
         SqlXmlCommand cmd = new SqlXmlCommand(ConnString);  
         cmd.CommandType = SqlXmlCommandType.TemplateFile;  
         cmd.CommandText = "TemplateFile.xml";  
         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. 請確定您電腦上已安裝 Microsoft .NET Framework。

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

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

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

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

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

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

如果您將參數傳遞至範本,參數名稱的開頭必須是符號 (@):例如,p.Name=“@ContactID”,其中 p 是 SqlXmlParameter 物件。

這是採用一個參數的更新範本。

<ROOT xmlns:sql="urn:schemas-microsoft-com:xml-sql">  
  <sql:header>  
     <sql:param name='ContactID'>1</sql:param>    
  </sql:header>  
  <sql:query>  
    SELECT ContactID, FirstName, LastName  
    FROM   Person.Contact  
    WHERE  ContactID=@ContactID  
    FOR XML AUTO  
  </sql:query>  
</ROOT>  

這是將參數傳入以執行範本的更新程序代碼。

public static int testParams()  
{  
  
   Stream strm;  
   SqlXmlParameter p;  
  
   SqlXmlCommand cmd = new SqlXmlCommand(ConnString);  
   cmd.CommandType = SqlXmlCommandType.TemplateFile;  
   cmd.CommandText = "TemplateFile.xml";  
   p = cmd.CreateParameter();  
   p.Name="@ContactID";  
   p.Value = "1";  
   strm = cmd.ExecuteStream();  
   StreamReader sw = new StreamReader(strm);  
   Console.WriteLine(sw.ReadToEnd());  
   return 0;        
}