使用存储过程在MySQL中批量插入

时间:2015-04-24 18:47:45

标签: mysql xml

从我的C#开始,我在运行时创建数据表。我想将此数据表传递给存储过程,以便将数据一起插入到表中。 我使用MySQL作为数据库。在SQL-Server中为多个插入传递xml的MySQL等价物是什么?

我从数据集生成XML并将其传递给存储过程:

CREATE DEFINER=`root`@`localhost` PROCEDURE `RouteLocationVehicleTimeInsert`(

    IN xml VARCHAR(1000000)
    )
BEGIN
  SET @x=1;
  SET @val=xml;
    WHILE @x<=4 DO
        SET @vehicleId=EXTRACTVALUE(@val, 'NewDataSet/Table1/vehicle_id[$@x]');
        SET @routeId = EXTRACTVALUE(@val, 'NewDataSet/Table1/route_id[$@x]');
        SET @locationId = EXTRACTVALUE(@val, 'NewDataSet/Table1/location_id[$@x]');
        SET @arrivalTime = EXTRACTVALUE(@val, 'NewDataSet/Table1/arrival_time[$@x]');   
    INSERT INTO `rm.routelocation_fm.vehicle_time`(`vehicle_id`,`route_id`,`location_id`,`arrival_time`)
    VALUES(@vehicleId,@routeId,@locationId,@arrivalTime);
    SET @x=@x+1;
   END WHILE;
END@@

但它没有帮助。当我测试用SP编写的sql语句时,i在同一列中给出multipl值,如下所示

SET @val='<NewDataSet>
<Table1>
<vehicle_id>1</vehicle_id>
<route_id>5</route_id>
<location_id>1</location_id>
<arrival_time>00:00</arrival_time>
</Table1>
<Table1>
    <vehicle_id>2</vehicle_id>
    <route_id>5</route_id>
    <location_id>2</location_id>
    <arrival_time>00:00</arrival_time>
  </Table1></NewDataSet>';
SET @x=1;

        SET @vehicle_id= EXTRACTVALUE(@val, 'NewDataSet/Table1/vehicle_id[1]');
        SELECT @vehicle_id;

它在同一列中给出结果为1 1。他们是两个记录。

2 个答案:

答案 0 :(得分:0)

In your bottom example you have <Table1></Table1> block twice. And as per definition in XML Functions documentation:

If multiple matches are found, the content of the first child text node of each matching element is returned (in the order matched) as a single, space-delimited string.

It returns the contents of first vehicle_id in both <Table1> blocks. If you want the id from just first <Table1>, change your XPath to 'NewDataSet/Table1[1]/vehicle_id[1]'.

答案 1 :(得分:0)

您的初始xpath:NewDataSet/Table1/vehicle_id[1]无效,因为它会从每个vehicle_id父级返回Table1。由于每个vehicle_id中只有一个Table1,因此xpath不会产生任何影响。

通常,为了从xpath获得第一个匹配,我们将整个xpath包装在()[1]中,如下所示:

(NewDataSet/Table1/vehicle_id)[1]

不幸的是,MySQL的EXTRACTVALUE()似乎不支持上述xpath语法。您需要采用更复杂的方法来获得类似的结果:

NewDataSet/Table1[vehicle_id][1]/vehicle_id[1]

在xpath上方,从第一个 vehicle_id获取 Table1,其中包含子vehicle_id

SQL Fiddle