SQL: split a variable

Status
You're currently viewing only C0rinthian's posts. Click here to go back to viewing the entire thread.
Not open for further replies.

C0rinthian

Ars Tribunus Angusticlavius
6,858
assuming worst case scenario where you don't know how long each section of the value is, you'll need to use instr to find positions and then substr to pull out portions.

So to pull out the first one, you use instr to find the position of the '.' and then use that to determine the length of the substr to extract:
Code:
substr( '12345.01' , 1 , instr( '12345.01' , '.' )- 1 )

And then for the second half, you do something similar, but working from the '.' to the end.

Code:
substr( '12345.01' ,  instr( '12345.01' , '.') - length( '12345.01' ))

instr syntax: instr('String_to_search', 'String_to_find', Start_position, occurrence)
substr syntax: substr('String', start_position, length)

Using a negative value for the start positions starts from the end and counts back. (So a start position of -4 starts 4 characters from the end of the string)
 

C0rinthian

Ars Tribunus Angusticlavius
6,858
Good points.

Also realized my second bit of code was inaccurate. (Corrected now) Regardless of where you start in the string, it then counts toward the end of the string. So if you do something like:
Code:
instr ( 'ThisIsAString', -4, 4)
it would return 'ring'

If you omit the length, it goes from the start point to the end of the string. So in your example, we can do:

Code:
substr( '12345.01' ,  instr('12345.01', '.') - length('12345.01'))

Which finds the position of the first '.' (6) and subtracts the total length of the string from that (8) giving you a starting position of -2, and then everything from that position to the end. '01'

This also addresses what Fristie mentions with the possibility of there being more than one '.' in the string, as everything works from the first occurrence.
 
Status
You're currently viewing only C0rinthian's posts. Click here to go back to viewing the entire thread.
Not open for further replies.