我創建了一個返回XML的存儲過程,我也希望在創建的方法中返回該XML。如何從存儲過程返回XML?
我有兩個問題。首先,在進行一些搜索之後,建議不要使用.ExecuteScalar();
,因爲它會截斷2033個字符以上的字符串。
於是,我找到了一個叫ExecuteXMlReader()
功能,但在Visual Web Developer 2010和學習表達對.NET 4.0(C#)運行時,它拋出錯誤"System.Data.SqlClient.SqlCommand' does not contain a definition for 'ExecuteXMlReader' and no extension method 'ExecuteXMlReader' accepting a first argument of type 'System.Data.SqlClient.SqlCommand' could be found"
這裏是我的存儲過程:
CREATE PROCEDURE dbo.GETReport
(@ReportDate date)
AS
SELECT * FROM ReportTbl
WHERE ReportDate = @ReportDate
for xml auto, elements
set nocount on;
RETURN
這裏是我的方法:
using System.Data;
using System.Data.SqlClient;
...
//connect
SqlConnection conn = new SqlConnection("Data Source=localhost; User Id=foo; Password=foo; Initial Catalog=Database1");
conn.Open();
//create command
SqlCommand cmd = new SqlCommand("dbo.GETReport", conn);
cmd.Parameters.AddWithValue("@ReportDate", "3/24/2011");
cmd.CommandType = CommandType.StoredProcedure;
DataReader rd = cmd.ExecuteXMlReader(); //this is where error is occuring
//also, it is throwing an error for DataReader as well saying there is no
//type of namespace with that name
rd.Read();
string s = rd.ReadOuterXml(); //also dont know if this is how i should return the XML
其次,除了ExecuteXMLReader()
問題,我不知道是否返回字符串是首先返回XML的正確方法...是否有另一個對象類型我應該將其轉換爲?或者我應該使用另一個函數?
預先感謝您!
工作很好,但問題很快..有沒有辦法將XML作爲XML返回而不是字符串? – AngeloS 2011-03-24 19:35:13
'XmlReader'是讀取任何XML的底層方法。例如,您將使用它來加載XDocument或XmlDocument,使用XDocument.Load(reader)。 – 2011-03-24 19:38:12
@Angelo,你可以使用類似於'XmlDocument document = new XmlDocument(); document.Load(reader);'或者像@John所說的那樣使用'XDocument.Load(reader)'。謝謝,@約翰! – Alex 2011-03-24 19:42:18