【问题标题】:Split one column value into multiple columns - stored procedure将一列值拆分为多列 - 存储过程
【发布时间】:2013-09-19 17:55:48
【问题描述】:

我有一个名为 product 的表,其中包含一个名为“Description”的列。描述列的值将类似于

'NAME:ITEM1;COST:20;QUANTITY:23;'
'NAME:ITEM2;COST:20;QUANTITY:23;'
'NAME:ITEM4;COST:24;QUANTITY:24;'
'NAME:ITEM6;COST:26;QUANTITY:25;'
'NAME:ITEM3;COST:27;QUANTITY:27;'

现在我有另一个名为PRODUCT_DETAILS 的表,它有三列NAMECOSTQUANTITY

我必须按':',';' 拆分值并将值单独提取到PRODUCT_DETAILS 表中。

我应该使用存储过程来做到这一点。请帮我解决这个问题,因为我只用 SQL 编写了简单的查询和存储过程

【问题讨论】:

  • 这是mysql还是oracle?
  • 您熟悉 Oracle 的 REGEXP 功能吗?如果是 - 使用它,否则学习它。您可能想使用this tutorial
  • 刚刚删除了标签
  • 谢谢大家。我可以有任何样品吗?我尝试了很多解决方案,包括上面的建议。但找不到解决办法

标签: sql oracle stored-procedures


【解决方案1】:

您不需要为此使用存储过程。正如您知道描述的格式,您可以轻松地选择值并将它们插入到 product_details 中:

插入 product_details (名称、成本、数量) 选择 substr(description, instr(description, ':', 1, 1) + 1, instr(description, ';', 1, 1) - instr(description, ':', 1, 1) - 1) 作为名称, to_number(substr(description, instr(description, ':', 1, 2) + 1, instr(description, ';', 1, 2) - instr(description, ':', 1, 2) - 1))作为成本, to_number(substr(description, instr(description, ':', 1, 3) + 1, instr(description, ';', 1, 3) - instr(description, ':', 1, 3) - 1))作为数量 来自产品;

当然你也可以写一个包含语句的过程:

创建或替换过程 product_to_product_details 是 开始 插入 product_details (名称、成本、数量) 选择 substr(description, instr(description, ':', 1, 1) + 1, instr(description, ';', 1, 1) - instr(description, ':', 1, 1) - 1) 作为名称, to_number(substr(description, instr(description, ':', 1, 2) + 1, instr(description, ';', 1, 2) - instr(description, ':', 1, 2) - 1))作为成本, to_number(substr(description, instr(description, ':', 1, 3) + 1, instr(description, ';', 1, 3) - instr(description, ':', 1, 3) - 1))作为数量 来自产品; 结尾;

【讨论】:

    【解决方案2】:

    这是一个示例查询,可帮助您拆分数据:

    SELECT REGEXP_REPLACE(str,'.*NAME:([^;]+);.*','\1') AS name
      ,REGEXP_REPLACE(str,'.*COST:([^;]+);.*','\1') AS cost
      ,REGEXP_REPLACE(str,'.*QUANTITY:([^;]+);.*','\1') AS quantity
    FROM SplitStringTest;
    

    这里有一个Fiddle 来演示。正则表达式是处理这类事情的一个非常方便的工具。

    以下是一些参考资料:

    Regex tutorial

    Oracle docs

    【讨论】:

    • 不客气!我希望这个对你有用。如果是这样,请考虑对有帮助的答案进行投票并接受有效的答案。祝你好运!
    猜你喜欢
    • 2017-10-03
    • 1970-01-01
    • 1970-01-01
    • 2013-01-23
    • 2014-12-16
    相关资源
    最近更新 更多