根据列的长度在Oracle中生成序列

Generate sequence in Oracle based on length of column

我需要在 Oracle 中根据列的长度和增量 2 生成序列。

For example:
Select comp_name from table_a
Output: COGNIZANT

所以我需要生成序列:

Generate_sequence ( min number , length (comp_name), incremental)

Meaning: sequence min val 1 , max value 9 and incremental of 2 即 (1, 9,2)

这里是9,因为我们的输出是cognizant,长度是9

生成序列的输出应该是

1
3
5
7
9

您可以创建用户自定义函数:

CREATE FUNCTION generate_series(
  i_start IN NUMBER,
  i_end   IN NUMBER,
  i_step  IN NUMBER DEFAULT 1
) RETURN SYS.ODCINUMBERLIST PIPELINED DETERMINISTIC
IS
  v_steps CONSTANT PLS_INTEGER := FLOOR((i_end - i_start)/i_step);
BEGIN
  FOR step_num IN 0 .. v_steps LOOP
    PIPE ROW (i_start + i_step * step_num);
  END LOOP;
END;
/

然后在table集合表达式中使用它:

SELECT *
FROM   TABLE(generate_series(1,3,0.7));

输出:

COLUMN_VALUE
1
1.7
2.4

如果你有 table:

CREATE TABLE table_a (comp_name) AS
SELECT 'COGNIZANT' FROM DUAL UNION ALL
SELECT 'ABCD' FROM DUAL;

然后:

SELECT comp_name,
       s.column_value
FROM   table_a
       CROSS JOIN TABLE(generate_series(1, LENGTH(comp_name), 2)) s

输出:

COMP_NAME COLUMN_VALUE
COGNIZANT 1
COGNIZANT 3
COGNIZANT 5
COGNIZANT 7
COGNIZANT 9
ABCD 1
ABCD 3

db<>fiddle here