Calling a Stored Procedure with XML Datatype

2020-03-02 05:01发布

I am simply trying to call a store procedure (SQL Server 2008) using C# and passing XMLDocument to a store procedure parameter that takes a SqlDbType.Xml data type. I am getting error: Failed to convert parameter value from a XmlDocument to a String. Below is code sample. How do you pass an XML Document to a store procedure that is expecting an XML datatype? Thanks.

        XmlDocument doc = new XmlDocument();
        //Load the the document with the last book node.
        XmlTextReader reader = new XmlTextReader(@"C:\temp\" + uploadFileName);
        reader.Read();
        // load reader 
        doc.Load(reader);

        connection.Open();

        SqlCommand cmd = new SqlCommand("UploadXMLDoc", connection);

        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Parameters.Add("@Year", SqlDbType.Int);
        cmd.Parameters["@Year"].Value = iYear;
        cmd.Parameters.Add("@Quarter", SqlDbType.Int);
        cmd.Parameters["@Quarter"].Value = iQuarter;
        cmd.Parameters.Add("@CompanyID", SqlDbType.Int);
        cmd.Parameters["@CompanyID"].Value = iOrganizationID;
        cmd.Parameters.Add("@FileType", SqlDbType.VarChar);
        cmd.Parameters["@FileType"].Value = "Replace";
        cmd.Parameters.Add("@FileContent", SqlDbType.Xml);
        cmd.Parameters["@FileContent"].Value = doc;
        cmd.Parameters.Add("@FileName", SqlDbType.VarChar);
        cmd.Parameters["@FileName"].Value = uploadFileName;
        cmd.Parameters.Add("@Description", SqlDbType.VarChar);
        cmd.Parameters["@Description"].Value = lblDocDesc.Text;
        cmd.Parameters.Add("@Success", SqlDbType.Bit);
        cmd.Parameters["@Success"].Value = false;
        cmd.Parameters.Add("@AddBy", SqlDbType.VarChar);
        cmd.Parameters["@AddBy"].Value = Page.User.Identity.Name;

        cmd.ExecuteNonQuery();
        connection.Close();

9条回答
beautiful°
2楼-- · 2020-03-02 05:19

In .NET Framework 4.5.2, I was able to pass a System.Xml.XmlDocument (variable name "xdoc") object using the following simple code:

XmlTextReader xreader = new XmlTextReader(new StringReader(xdoc.OuterXml));
cmd.Parameters.Add(new SqlParameter("@xmlOptions", new SqlXml(xreader)));
查看更多
We Are One
3楼-- · 2020-03-02 05:21

Another simpler way is to write the xmldoc to a string and pass that to the stored procedure.

Dim sb As New StringBuilder()
Dim wrtr As New System.IO.StringWriter(sb)
doc.Save(wrtr)
Dim strxml As String = sb.ToString()
cmd.Parameters.Add("@FileContent", SqlDbType.Xml);
cmd.Parameters["@FileContent"].Value =strxml;
查看更多
在下西门庆
4楼-- · 2020-03-02 05:25

you can add parameter in more simpler way in this way we don't have to pass object type to parameter sql manages it as passed value

SqlXml sqlXml = new SqlXml(xmlReader); 
cmd.Parameters.AddWithValue("@FileContent"], strxml);
查看更多
登录 后发表回答