2

In a column I have "1;2;3;6-9"

I need make this string in a array like this (1,2,3,6,7,8,9)

select range from my_table

return

| range     |
|-----------| 
| 1;2;3;6-9 |

I need run

select id from my_another_table where id in("1;2;3;6-9")
| id |
|----| 
| 1  |
| 2  |
| 3  |
| 6  |
| 7  |
| 8  |
| 9  |
2
  • 1
    Do you have to do this in SQL? Can you do it in your application code instead? Commented Feb 8, 2019 at 23:04
  • I need do this in sql :( Commented Feb 8, 2019 at 23:06

3 Answers 3

3

This is a lousy structure for data. But you can do this with generate_series() and string functions:

select generate_series(v2.lo, v2.hi, 1)
from (values ('1;2;3;6-9')) v(str) cross join lateral
     regexp_split_to_table(v.str, ';') as r(range) cross join lateral
     (values (case when range not like '%-%' then range::int else split_part(range, '-', 1)::int end,
              case when range not like '%-%' then range::int else split_part(range, '-', 2)::int end
             )
     ) v2(lo, hi);
Sign up to request clarification or add additional context in comments.

Comments

1

Just in case that you are still interested, you can create a function.

create or replace function parse_ranges(value TEXT) returns setof int as
$func$
DECLARE
    range RECORD;
    ra int;
    rb int;
BEGIN
    FOR range IN SELECT * FROM regexp_split_to_table(value, ';') as r(r) LOOP
        IF range.r LIKE '%-%' THEN
            ra = split_part(range.r, '-', 1)::int;
            rb = split_part(range.r, '-', 2)::int;
            RETURN QUERY SELECT * FROM generate_series(ra, rb, 1);
        ELSE
            RETURN NEXT range.r::int;
        END IF;
    END LOOP;
END;
$func$
LANGUAGE plpgsql;

Then you can use it:

select id from my_another_table where id in(SELECT parse_ranges('1;2;3;6-9'))

Comments

0
    SELECT *
      FROM [dbo].[Table_1] 
     where Id in (select [value] from openjson((select conf.[Value] FROM Table_2 conf WHERE conf.[Key]='Range'), '$'))

Where

Table_2 "data must be JSon" range (Nvarchar) =>'[1,2,3,4]'

Table_1 ID Int => 1,2,4,5

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.