sql—如何将多个逗号分隔的字符串转换为具有多个列的表

rm5edbpk  于 2021-08-13  发布在  Java
关注(0)|答案(1)|浏览(365)

我在数据库中有一个包含两列(id,asset)的表。现在我需要将一个元组列表(id1,id2,qty)传递给存储过程,并按qty减少id2的资产并将其添加到id1。我想到了将这些值作为三个逗号分隔的字符串传递,每个字符串中的元素数长度相同。然后我要解析这些字符串并将它们转换为临时表,最后进行所需的计算和更新。例如,对于以下输入id1:101231452176 id2:301453,541265 qty:1000200074126521,结果表应如下所示:

ID1 |   ID2  |  QTY
--------------------
101 |   301  |  1000
231 |   453  |  2000
452 |   54   |  7412
176 |   1265 |  6521
guicsvcw

guicsvcw1#

您可以使用如下“标记器”函数:

select 
  id1.seq
, id1.tok as id1
, id2.tok as id2
, qty.tok as qty
from xmltable('for $id in tokenize($s, ",") return <i>{string($id)}</i>' 
passing '101,231,452,176' as "s"
columns 
  seq for ordinality
, tok int path '.'
) id1
join xmltable('for $id in tokenize($s, ",") return <i>{string($id)}</i>' 
passing '301,453,54,1265' as "s"
columns 
  seq for ordinality
, tok int path '.'
) id2 on id2.seq = id1.seq 
join xmltable('for $id in tokenize($s, ",") return <i>{string($id)}</i>' 
passing '1000,2000,7412,6521' as "s"
columns 
  seq for ordinality
, tok int path '.'
) qty on qty.seq = id1.seq;

结果是:

|SEQ                 |ID1        |ID2        |QTY        |
|--------------------|-----------|-----------|-----------|
|1                   |101        |301        |1000       |
|2                   |231        |453        |2000       |
|3                   |452        |54         |7412       |
|4                   |176        |1265       |6521       |

参数可以用来代替后面的字符串常量 passing 每个 xmltable .

相关问题