2010-11-25 30 views
1

我有一些代碼:sproc using'for xml',然後在C#中使用ExecuteXmlReader - >「數據爲空,此方法或屬性不能在空值上調用。」

XmlDocument doc = new XmlDocument(); 

using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["LocalSqlServer"].ToString())) 
      { 
       SqlCommand command = connection.CreateCommand(); 

       command.CommandText = "sproc1"; 
       command.CommandType = CommandType.StoredProcedure; 

       command.Parameters.Add(
         new SqlParameter("@Param1",2)); 

       connection.Open(); 
       doc.Load(command.ExecuteXmlReader()); 
      } 

它加載從一個存儲過程的XML文檔。我得到:

數據爲空。無法在Null值上調用此方法或屬性。

當存儲過程,因爲它使用返回null

for xml raw, type, root('rows') 

改造表格結果轉換成XML。

我該如何避免這種情況?無論是在我的SQL代碼或在C#中處理它?

謝謝。

Chris

回答

1

圍繞我迄今找到的最好的工作是在我的SQL代碼來使用:

DECLARE @XML XML; 
... 
SELECT @XML = (select 
... 
for xml raw, type, root('rows')) 
... 
select case when @XML is not null then @XML else '<rows></rows>' end 
0

好的。那麼這段代碼呢?

connection.Open(); 
SqlDataAdapter adapter = new SqlDataAdapter(command); 
DataTable table = new DataTable(); 
adapter.Fill(table); 
if (table.Rows.Count > 0) 
{ 
    using (MemoryStream stream = new MemoryStream()) 
    { 
     XmlWriter writer = XmlTextWriter.Create(stream); 
     table.WriteXml(writer); 
     XmlReader reader = XmlReader.Create(stream); 
     doc.Load(reader); 
    } 
} 
+0

我想在此之前 - command.ExecuteXmlReader拋出一個異常:{「數據爲空,這方法或屬性不能在空值上調用。「} – cs0815 2010-11-25 15:03:02

+0

@csetzkorn - 對不起,認爲加載拋出了execption。將嘗試尋找替代品。 – 2010-11-25 15:04:09

相關問題