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 物件。

例外狀況

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

-或-

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

-或-

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

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

-或-

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

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

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

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

範例

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

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();
    }
}
Public Sub CreateXMLReader(ByVal queryString As String, _
    ByVal connectionString As String)

    Using connection As New SqlConnection(connectionString)
        connection.Open()

        Dim command As New SqlCommand(queryString, connection)
        Dim reader As System.Xml.XmlReader = command.ExecuteXmlReader
    End Using
End Sub

備註

這個方法所傳回的 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 個字元的多個數據列傳回任何大於 2,033 個字元的 XML 結果。 若要避免這種行為,請使用 ExecuteXmlReaderBeginExecuteXmlReader 來讀取 FOR XML 查詢。

適用於

另請參閱