C#/SQL - What's wrong with SqlDbType.Xml in procedures?

不问归期 提交于 2019-11-28 02:01:53
Gregory A Beamer

It does work. You will have to set up the Value as SqlXml and not a string, but it can be done. Imagine this table:

CREATE TABLE XmlTest
(
    [XmlTestId] [int]   identity(1,1) primary key,
    [XmlText]   [xml]   NOT NULL
)

And the sproc:

CREATE PROCEDURE XmlTest_Insert
(
    @XmlText    xml
)
AS

INSERT INTO XmlTest (XmlText)
VALUES (@XmlText)

Now picture a console application that looks like this:

using System.Data.SqlClient;
using System.Data;
using System.Data.SqlTypes;
using System.Xml;

namespace TestConsole
{
    class Program
    {

        static void Main(string[] args)
        {
            string xmlDoc = "<root><el1>Nothing</el1></root>";
            string connString = "server=(local);database=IntroDB;UID=sa;PWD=pwd";
            SqlConnection conn = new SqlConnection(connString);
            SqlCommand cmd = new SqlCommand("XmlTest_Insert", conn);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlParameter param = new SqlParameter("@XmlText", SqlDbType.Xml);
            param.Value = new SqlXml(new XmlTextReader(xmlDoc
                           , XmlNodeType.Document, null));
            cmd.Parameters.Add(param);

            conn.Open();
            cmd.ExecuteNonQuery();
            conn.Dispose();
        }
    }
}

Bingo!

This was done in Visual Studio 2008 (.NET 3.5), but I am fairly sure it should work in Visual Studio 2005 (2.0 Framework), as well.

Instead of using the Add Method, try using AddWithValue where you do not need to specify the type just the name and the value. Unless you are using a different direction to input?

Jaydeep Shil
//Create The StringWriter Object

var stringWriter = new System.IO.StringWriter();

//Create XmlSerializer Object for the serialization,
RequestUpdateRBCustomerExternal is the Class of which type having all the values

var serializer = new XmlSerializer(typeof(RequestUpdateRBCustomerExternal));

//request is of type RequestUpdateRBCustomerExternal

serializer.Serialize(stringWriter, request);

SqlXml xml = new SqlXml(new XmlTextReader(stringWriter.ToString(), XmlNodeType.Document, null));

cmd.CommandText ="insert into SAPDataTracking values('"+DateTime.Now+"','"+xml.Value+"')";
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!