gpt4 book ai didi

sql - 在DB2中拆分VARCHAR以检索内部的值

转载 作者:行者123 更新时间:2023-12-04 14:29:49 27 4
gpt4 key购买 nike

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

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' )
;

我想提取第四个字段...
'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'

我按此顺序搜索:
  • DB2内置字符串函数
  • 可嵌入的语句,例如SUBSTR(COL, POSSTR(COL)+1)...
  • 用户定义的函数,其行为类似于SPLIT

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

    最佳答案

    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;

    关于sql - 在DB2中拆分VARCHAR以检索内部的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1305804/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com