0

Is there a way i could convert an actual string to a number in postgresql

i have record stored in db and below is an example of unique identifier found in each record.

d895774d-7b91-4adc-bfba-f1264e5aae04

I want to store this record in another database but i would want to generate another unique number for each transaction/line

Is there a way i can convert this d895774d-7b91-4adc-bfba-f1264e5aae04 to some number. like this actual numbers 13693660123082308270370273012321321312321

select 'd895774d-7b91-4adc-bfba-f1264e5aae04' as id
Omari Victor Omosa
  • 2,814
  • 2
  • 24
  • 46
  • remove the dashes, then convert the hex value to [a number](https://stackoverflow.com/questions/8316164/convert-hex-in-text-representation-to-decimal-number) –  Mar 17 '21 at 19:23

1 Answers1

4

First convert the string into a table of single characters (the from clause);
Then select the digits 'as is', a as 10, b as 11 and so on (the case expression);
Finally aggregate into a string (string_agg) skipping the - characters (where clause).

select 
    string_agg(case when c between '0' and '9' then c else (ascii(c) - 87)::text end, '') 
 from unnest(string_to_array('d895774d-7b91-4adc-bfba-f1264e5aae04', null)) c
 where c <> '-';

Result: 13895774137119141013121115111015126414510101404

  • Edit
select 
  td.date, 
  (
   select string_agg(case when c between '0' and '9' then c else (ascii(c) - 87)::text end, '') 
   from unnest(string_to_array(td.id, null)) c
   where c <> '-'
  ) as id
from table_d td;

Stefanov.sm
  • 11,215
  • 2
  • 21
  • 21