簡體   English   中英

從XML插入到SQL Server表

[英]Insert from xml to sql server table

我有以下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

我該如何解決?

將XML傳遞到SQL Server並從那里進行處理可能會更簡單。

您只需要一個接受xml值作為參數的存儲過程:

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

在存儲的proc中,您可以操縱xml來提取值並執行INSERT ,如下所示。

演示SQL小提琴

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM