问题描述
我创建了一个返回 XML 的存储过程,我还想在我创建的方法中返回该 XML.
I created a Stored Procedure that returns XML and I would like to also return that XML in a method I created.
我有两个问题.首先,经过一番搜索,不建议使用.ExecuteScalar();
,因为它会截断超过2033个字符的字符串.
I'm having two issues. First, after doing some searching, it is not advised to use .ExecuteScalar();
because it truncates strings over 2033 characters.
因此,我找到了一个名为 ExecuteXMlReader()
的函数,但在运行于 .NET 4.0 (C#) 的 Visual Web Developer 2010 Express 中,它抛出错误 System.Data.SqlClient.SqlCommand' 不包含 'ExecuteXMlReader' 的定义,并且无法找到接受类型为 'System.Data.SqlClient.SqlCommand' 的第一个参数的扩展方法 'ExecuteXMlReader'"
So, I found a function called ExecuteXMlReader()
, but in Visual Web Developer 2010 Express that runs on .NET 4.0 (C#) it is throwing the error "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的正确方式......是否还有另一种对象类型我应该转换成??或者我应该使用的其他功能??
Second, in addition to the ExecuteXMLReader()
issue, I don't know if returning a string is the proper way of returning XML in the first place... Is there another object type I should convert it to?? Or another function I should use??
提前谢谢你!!
推荐答案
首先,SqlCommand
有一个 ExecuteXmlReader
方法,而不是你的 ExecuteXMlReader
写道(这是拼写错误).二、SqlCommand.ExecuteXmlReader
方法返回 XmlReader
类型的值,而不是您的示例中的 DataReader
类型.因此,将您的代码更改为:
First, SqlCommand
has a ExecuteXmlReader
method, not ExecuteXMlReader
as you wrote (this is misspelling). Second, SqlCommand.ExecuteXmlReader
method returns a value of type XmlReader
, not a DataReader
as is in your example. So changing your code to:
using (XmlReader reader = cmd.ExecuteXmlReader())
{
while(reader.Read())
{
string s = reader.ReadOuterXml();
// do something with s
}
}
应该可以解决问题.
这篇关于如何从存储过程返回 XML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!