How to pass XML from C# to a stored procedure in SQL Server 2008?
Posted
by
Geetha
on Stack Overflow
See other posts from Stack Overflow
or by Geetha
Published on 2010-08-30T11:59:50Z
Indexed on
2012/04/14
5:29 UTC
Read the original article
Hit count: 173
I want to pass xml document to sql server stored procedure such as this:
CREATE PROCEDURE BookDetails_Insert (@xml xml)
I want compare some field data with other table data and if it is matching that records has to inserted in to the table.
Requirements:
How do I pass XML to the stored procedure? I tried this, but it doesn’t work:[Working]
command.Parameters.Add( new SqlParameter("@xml", SqlDbType.Xml) { Value = new SqlXml(new XmlTextReader(xmlToSave.InnerXml, XmlNodeType.Document, null)) });
How do I access the XML data within the stored procedure?
Edit: [Working]
String sql = "BookDetails_Insert";
XmlDocument xmlToSave = new XmlDocument();
xmlToSave.Load("C:\\Documents and Settings\\Desktop\\XML_Report\\Books_1.xml");
SqlConnection sqlCon = new SqlConnection("...");
using (DbCommand command = sqlCon.CreateCommand())
{
**command.CommandType = CommandType.StoredProcedure;**
command.CommandText = sql;
command.Parameters.Add(
new SqlParameter("@xml", SqlDbType.Xml)
{
Value = new SqlXml(new XmlTextReader(xmlToSave.InnerXml
, XmlNodeType.Document, null))
});
sqlCon.Open();
DbTransaction trans = sqlCon.BeginTransaction();
command.Transaction = trans;
try
{
command.ExecuteNonQuery();
trans.Commit();
sqlCon.Close();
}
catch (Exception)
{
trans.Rollback();
sqlCon.Close();
throw;
}
Edit 2: How to create a select query to select pages, description based on some conditions.
<booksdetail> <isn_13>700001048</isbn_13> <isn_10>01048B</isbn_10>
<Image_URL>http://www.landt.com/Books/large/00/7010000048.jpg</Image_URL>
<title>QUICK AND FLUPKE</title> <Description> PRANKS AND JOKES QUICK AND FLUPKE </Description> </booksdetail>
© Stack Overflow or respective owner