共用方式為


在用戶端上處理 XML (SQLXML Managed 類別)

適用於:SQL ServerAzure SQL 資料庫

此範例說明 ClientSideXml 屬性的使用。 應用程式會在伺服器上執行預存程式。 預存程序的結果(雙欄數據列集)會在客戶端進行處理,以產生 XML 檔。

下列 GetContacts 預存程式會傳回 AdventureWorks 資料庫中 Person.Contact 數據表中員工的 FirstNameLastName

USE AdventureWorks2022;
CREATE PROCEDURE GetContacts @LastName varchar(20)  
AS  
SELECT FirstName, LastName  
FROM   Person.Contact  
WHERE LastName = @LastName  
Go  

這個 C# 應用程式會執行預存程式,並在指定 CommandText 值時指定 FOR XML AUTO 選項。 在應用程式中,SqlXmlCommand 物件的 ClientSideXml 屬性會設定為 true。 這可讓您執行預先存在的預存程式,以傳回數據列集,並在用戶端上套用 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;  
         SqlXmlParameter p;  
         SqlXmlCommand cmd = new SqlXmlCommand(ConnString);  
         cmd.ClientSideXml = true;  
         cmd.CommandText = "EXEC GetContacts ? FOR XML NESTED";  
         p = cmd.CreateParameter();  
         p.Value = "Achong";  
         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. 建立預存程式。

  2. 將這個範例中提供的 C# 程式代碼 (DocSample.cs) 儲存在資料夾中。 編輯程式代碼以指定適當的登入和密碼資訊。

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

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

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

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