共用方式為


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

例外狀況

當 設定為 Stream時,會使用除 BinaryVarBinary 以外的 。ValueSqlDbType 欲了解更多串流資訊,請參閱 SqlClient 串流支援

-或-

SqlDbType除了 Char、NChar、NVarChar、VarCharXml,當 Value 設定為 TextReader時,會使用其他 CharNChar、NVarChar、VarChar 或 Xml。

-或-

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

在執行指令時發生了例外,該指令在鎖定列時發生。 當你使用 Microsoft .NET Framework 1.0 版本時,此例外不會產生。

-或-

串流操作中發生了一次超時。 欲了解更多串流資訊,請參閱 SqlClient 串流支援

SqlConnection 串流操作中關閉或掉落。 欲了解更多串流資訊,請參閱 SqlClient 串流支援

在串流操作中,物件或 發生StreamXmlReaderTextReader錯誤。 欲了解更多串流資訊,請參閱 SqlClient 串流支援

Stream該 , XmlReaderTextReader物件在串流操作中被關閉。 欲了解更多串流資訊,請參閱 SqlClient 串流支援

範例

以下範例建立 a 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 指定一個語句,回傳 ntextnvarchar 包含有效 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 查詢。

適用於

另請參閱