在DB2中拆分VARCHAR以检索其中的值

在DB2中拆分VARCHAR以检索其中的值

本文介绍了在DB2中拆分VARCHAR以检索其中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 VARCHAR 列,其中包含5个信息(2 CHAR(3)和3 TIMESTAMP )用' $ '分隔。

I have a VARCHAR column that contains 5 informations (2 CHAR(3) and 3 TIMESTAMP) separated with '$'.

CREATE TABLE MYTABLE (
  COL VARCHAR(256) NOT NULL
);

INSERT INTO MYTABLE
VALUES
    ( 'AAA$000$2009-10-10 10:50:00$null$null$null' ),
    ( 'AAB$020$2007-04-10 10:50:00$null$null$null' ),
    ( 'AAC$780$null$2007-04-10 10:50:00$2009-04-10 10:50:00$null' )
;

我想提取第4个字段...

I would like to extract the 4th field ...

'AAA$000$2009-10-10 10:50:00$null$null$null'
                             ^^^^ this field

...有一些像

SELECT SPLIT(COL, '$', 4) FROM MYTABLE

1
-----
'null'
'null'
'2009-04-10 10:50:00'

我正在搜索该订单:


  1. DB2内置字符串函数

  2. 嵌入式语句,如 SUBSTR(COL,POSSTR(COL)+1)...

  3. 一个用户定义的函数, SPLIT

  1. A DB2 build-in string function
  2. An embeddable statement such as SUBSTR(COL, POSSTR(COL)+1)...
  3. An user defined function that behaves like SPLIT

精度:是,我知道这样的列不是一个好主意...

Precision : Yes, I do know that it's not a good idea to have such columns...

推荐答案

CREATE FUNCTION split(pos INT, delimeter CHAR, string VARCHAR(255))
LANGUAGE SQL
RETURNS VARCHAR(255)
DETERMINISTIC NO EXTERNAL ACTION
BEGIN ATOMIC
    DECLARE x INT;
    DECLARE s INT;
    DECLARE e INT;

    SET x = 0;
    SET s = 0;
    SET e = 0;

    WHILE (x < pos) DO
        SET s = locate(delimeter, string, s + 1);
        IF s = 0 THEN
            RETURN NULL;
        END IF;
        SET x = x + 1;
    END WHILE;

    SET e = locate(delimeter, string, s + 1);
    IF s >= e THEN
        SET e = LENGTH(string) + 1;
    END IF;
    RETURN SUBSTR(string, s + 1, e - s -1);
END!

用法:

SELECT split(3,'$',col) from mytable; -- or
SELECT split(0,'-', 'first-second-third') from sysibm.sysdummy1;
SELECT split(0,'-', 'returns this') from sysibm.sysdummy1;
SELECT split(1,'-', 'returns null') from sysibm.sysdummy1;

这篇关于在DB2中拆分VARCHAR以检索其中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 19:25