简体   繁体   English

为什么此存储过程仅插入一项?

[英]Why is this stored procedure only inserting one item?

Okay, so, I'm very new to SQL Server 2008 But my mission is to create a procedure that will simply load in some XML file from somewhere and parse its name and data into a single two-column table. 好的,所以,我对SQL Server 2008来说是一个新手,但是我的任务是创建一个过程,该过程将简单地从某个位置加载一些XML文件并将其名称和数据解析到单个两列表中。

Here's a general idea of what the contents of a given file will look like (though it contains about 100 actual entries): 这是给定文件内容的大致概念(尽管它包含大约100个实际条目):

<root>
<data name="Sword of Doom" xml:space="preserve"><value>+1 to Nubs</value></data>
<data name="Sword of Doom+1" xml:space="preserve"><value>+2 to Nubs</value></data>
</root>

Right, easy enough, right? 对,足够容易,对吗? I wish. 我希望。 The following script will it will run through the entire file (I know this because my file had an illegal character it encountered towards the end), but it WON'T create a table with more than one entry in it (namely, it only inserts the first entry of the XML file). 下面的脚本将整个文件运行(我知道这是因为我的文件有它接近尾声时遇到非法字符),但它不会创建一个表,在它(多个条目,即它只插入XML文件的第一个条目)。 I've tried seeing if it's an encoding issue, by saving it in notepad as well as Notepad++ under different things... but, nope. 我尝试通过将其保存在记事本以及Notepad ++中的不同内容中来查看它是否是编码问题,但是,不是。

I don't understand, what am I doing wrong here? 我不明白,我在这里做错了什么? Is it with how I'm bulk loading? 我要如何批量加载?

    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO

   CREATE PROCEDURE TestParse AS
    BEGIN
    IF OBJECT_ID('dbo.TRANS', 'U') IS NOT NULL
        DROP TABLE TRANS
    DECLARE @XmlFile XML
    SELECT @XmlFile = BulkColumn
    FROM OPENROWSET(BULK 'C:/TestTest.xml', SINGLE_BLOB) as x

    CREATE TABLE dbo.TRANS
    (
        NAME VARCHAR(255),
        DATA VARCHAR(255)
    )
    BEGIN
        INSERT INTO TRANS
        (
            NAME,
            DATA
        )
        SELECT
            x.TRANS.value('(/root)[1]','varchar(255)') AS DATA,
            x.TRANS.value('(/root/data/@name)[1]', 'varchar(255)') AS NAME
        FROM @XmlFile.nodes('/root') AS x (TRANS)
    END
    select * from TRANS
END
GO

The contents of the selection is always a single row NAME containing 'Sword of Doom' and DATA containing '+1 to Nubs'. 选择的内容始终是包含“末日之剑”的单行NAME和包含“ +1至Nubs”的DATA。 Only one row is ever effected by this stored procedure when I call it ('exec TestParse'). 当我调用它时(“ exec TestParse”),该存储过程只会影响到一行。

Any guidance here would be helpful. 这里的任何指导都会有所帮助。

To get 2 rows you have to pass root/data into nodes() function: 要获得2行,您必须将root/data传递到nodes()函数中:

select
    x.TRANS.value('(value/text())[1]','varchar(255)') as DATA,
    x.TRANS.value('@name', 'varchar(255)') as NAME
from @XmlFile.nodes('/root/data') as x(TRANS)

sql fiddle demo sql小提琴演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM