【问题标题】:Insert from xml to sql server table从xml插入到sql server表
【发布时间】:2014-09-16 14:34:47
【问题描述】:

我有以下 XML 文件:

<test>
    <test2>
        <A>206942</A>
    </test2>
    <test2>
        <A>203405</A>
    </test2>
</test>

我需要插入到 SQL Server 表中:

XmlNodeList dataNodes = xmlDoc.SelectNodes("/test/test2");

SqlConnection dbConnection = new SqlConnection(connectionString);
try
{
    dbConnection.Open();

    foreach (XmlNode node in dataNodes)
    {
        String A = (node.SelectSingleNode("A") != null) ?
          node.SelectSingleNode("A").InnerText.ToString() : string.Empty;
        try
        {
            using (SqlCommand cmd = dbConnection.CreateCommand())
            {
                cmd.Parameters.AddWithValue(" @A", A);
                cmd.ExecuteNonQuery();
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
}

我尝试上面的代码,我总是得到以下错误:

Incorrect syntax near @A Must declare the scalar variable @A

我该如何解决这个问题?

【问题讨论】:

  • 您尝试运行的 SQL 是什么?没有为SqlCommand 设置实际的CommandText。此外,AddWithValue 中的 @ 左侧还有一个空格。
  • 另外,XML 文档有多大?意思是,您希望有多少个“/test/test2”节点?如果很多,有一个选项会相当有效,并且不需要将 XML 传递给 SQL Server 进行解析。

标签: c# sql-server xml


【解决方案1】:

将 XML 传递给 SQL Server 并从那里处理它可能会更简单。

您只需要一个接受 xml 值作为参数的存储过程:

CREATE PROCEDURE [InsertXMLValuesToMyTable]
    @XML xml
AS 
BEGIN...

在存储过程中,您可以操作 xml 以提取值并执行INSERT,如下所示。

Demo SQL Fiddle

DECLARE @XML xml = 
    '<test>
        <test2>
            <A>206942</A>
        </test2>
        <test2>
            <A>203405</A>
        </test2>
    </test>';

-- this will convert the values into rows and add them to a temp table
SELECT T.r.value('.','int') IdsToInsert
INTO #TMP 
FROM @XML.nodes('test/test2/A') as T(r) 

-- mock object to insert into 
CREATE TABLE #TMP2 (ID int)

-- insert values from the first table into your destination table
INSERT INTO #TMP2
SELECT IdsToInsert 
FROM #TMP

-- show the output
SELECT * 
FROM #TMP2

DROP TABLE #TMP
DROP TABLE #TMP2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-30
    • 1970-01-01
    • 2013-06-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多