Share via


SqlCommand.ExecuteXmlReader 方法

定義

CommandText 傳送至 Connection 並建置 XmlReader 物件。

public:
 System::Xml::XmlReader ^ ExecuteXmlReader();
public System.Xml.XmlReader ExecuteXmlReader ();
member this.ExecuteXmlReader : unit -> System.Xml.XmlReader
Public Function ExecuteXmlReader () As XmlReader

傳回

XmlReader 物件。

例外狀況

SqlDbType當 設定 Stream 為 時 Value ,使用了BinaryVarBinary以外的 。 如需串流的詳細資訊,請參閱 SqlClient 串流支援

-或-

SqlDbType當 設定 TextReader 為 時 Value ,會使用CharNCharNVarCharVarCharXml以外的 。

-或-

SqlDbType當 設定 XmlReader 為 時 Value ,會使用Xml以外的 。

對鎖定的資料列執行命令時發生例外狀況。 當您使用 Microsoft .NET Framework 1.0 版時不會產生這個例外狀況。

-或-

串流作業期間發生逾時。 如需串流的詳細資訊,請參閱 SqlClient 串流支援

在串流作業期間已關閉或卸除的 SqlConnection。 如需串流的詳細資訊,請參閱 SqlClient 串流支援

在串流作業期間, XmlReaderTextReader 物件中 Stream 發生錯誤。 如需串流的詳細資訊,請參閱 SqlClient 串流支援

XmlReaderStream 串流作業期間,或 TextReader 物件已關閉。 如需串流的詳細資訊,請參閱 SqlClient 串流支援

範例

下列範例會建立 , SqlCommand 然後使用 來執行它 ExecuteXmlReader 。 此範例會傳遞字串,該字串是 Transact-SQL FOR XML SELECT 語句,以及用來連接到資料來源的字串。

using System;
using System.Data;
using Microsoft.Data.SqlClient;

private static void CreateXMLReader(string queryString,
    string connectionString)
{
    using (SqlConnection connection = new SqlConnection(
               connectionString))
    {
        connection.Open();
        SqlCommand command = new SqlCommand(queryString, connection);
        System.Xml.XmlReader reader = command.ExecuteXmlReader();
    }
}

備註

這個方法所傳回的 XmlReader 不支援非同步作業。 屬性 CommandText 通常會指定具有有效 FOR XML 子句的 Transact-SQL 語句。 不過, CommandText 也可以指定傳回 ntext 的 語句,或 nvarchar 包含有效 XML 的資料,或以 xml 資料類型定義之資料行的內容。

一般 ExecuteXmlReader 查詢的格式可以如下列 Microsoft Visual C# 範例所示:

SqlCommand command = new SqlCommand("SELECT * FROM dbo.Customers FOR XML AUTO, XMLDATA", SqlConn);

這個方法也可以用來擷取包含 XML 資料的單一資料列單一資料行結果集。 在此情況下,如果傳回多個資料列,方法會將 ExecuteXmlReader 附加 XmlReader 至第一個資料列的值,並捨棄結果集的其餘部分。

多個作用中結果集 (MARS) 功能允許使用相同連線的多個動作。

如果您使用 ExecuteReaderBeginExecuteReader 存取 XML 資料,SQL Server會傳回長度大於 2,033 個字元的任何 XML 結果,每個資料列各 2,033 個字元。 若要避免這種行為,請使用 ExecuteXmlReaderBeginExecuteXmlReader 來讀取 FOR XML 查詢。

適用於