How to return the second to last character in a string using SQL - sql

I am trying to only return the second to last character from a string using MS SQL.
I've tried using MID and Substring but the length of the string isn't always the same for the column I am trying to return, So I can't do it that way.
So say I am returning the codes of something:
Code
'1234'
I want to just return '3' from that code.
How can I do this?
Cheers in advance :)

Use SUBSTRING and LEN. LEN gives you the length of the string, then subtract 1 to get the previous char:
SELECT SUBSTRING(Code, LEN(Code)-1,1)

How about
select left(right(code, 2), 1) from MyTable;
You might need to validate that the string actually has at least 2 chars, however.
SqlFiddle here

Related

Check if a string has a combination of a substring and numbers in sql

how do I write a SQL where statement that checks if a string contains some substring and a number. For example:
string: macsea01
where string like 'macsea' plus a number
Regex is the most obvious solution to this question. Without more detail about the specific format of the string, I can suggest the following, which will match a sequence of a letter in the alphabet followed immediately by a digit:
where column_name like '%[a-zA-Z][0-9]%'
If you're literally looking for macsea at the beginning of the string followed by a digit, it would be:
where column_name like 'macsea[0-9]%'
Regex seem to bee a little slippery here, depending on your needs you can for instance divide the string into several parts, first the text part, and take the rest of the string, try to convert it into a number.
Somthing like this (but I think this perticular code is broken
where substring(column_name, 1, 6) = 'macsea' and cast(substring(column_name, 7, 1000) as int) > 0

How to determine if a variable has a special character using dual table on sql?

I'm currently trying to check if a string has a special character (value that is not 0 to 9 A to Z a to z), but the inhouse language that I'm currently using has a very limited function to do it (possible but it will take a lot of lines). but I am able to do a query on sql. Now I would like to ask if it is possible to query using the dual table on sql, My plan is to pass the string to variable and this variable will be use on my sql command. Thanks in advance.
Here is what you can use
SELECT REGEXP_INSTR('Test!ing','[^[:alnum:]]') FROM dual;
This will return a number other than 0 whenever your string has anything other than letters or numbers.
You can use TRANSLATE to remove all okay characters from the string. You get back a string containing only undesired characters - or an empty string when there are none.
select translate(
'AbcDefg1234%99.26éXYZ', -- your string
'.ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
'.') from dual;
returns: %.é

split string with character

using SQL 2008; I have the following string:
EMCo: 1 WorkOrder: 12770 WOItem: 10
I am trying to get the WorkOrder #.
When the string did not have the WOItem on end of it, I was able to use the following statement to get WorkOrder #.
[WorkOrder] = LTRIM(RTRIM(RIGHT(HQMA.KeyString,CHARINDEX(':',REVERSE(HQMA.KeyString))-1)))
This statement moves and may have double digits for the Co#, and it does not always have WOItem #. Was hoping to find something that would split after the ":" and just take 2nd group.
Any suggestions?
The patindex suggestion above will work beautifully, now if you still want to use your current statement, substring will pull the same values, and replace will take out WOItem. Not very elegant, it works whether you have WOItem or not:
select substring(LTRIM(RTRIM(RIGHT(REPLACE(HQMA.KeyString,'WOItem:',''),
CHARINDEX(':',REVERSE(REPLACE(HQMA.KeyString,'WOItem:','')))-1))),0,7)
select substring(LTRIM(RTRIM(RIGHT(REPLACE(HQMA.KeyString,'WOItem:',''),
CHARINDEX(':',REVERSE(REPLACE(HQMA.KeyString,'WOItem:','')))-1))),0,7)
How about using patindex()? Assuming the work order always has five characters:
select substring(HQMA.KeyString,
patindex('%WorkOrder: %', HQMA.KeyString) + 11,
5) as WorkOrder

SQL: Finding dynamic length characters in a data string

I am not sure how to do this, but I have a string of data. I need to isolate a number out of the string that can vary in length. The original string also varies in length. Let me give you an example. Here is a set of the original data string:
:000000000:370765:P:000001359:::3SA70000SUPPL:3SA70000SUPPL:
:000000000:715186816:P:000001996:::H1009671:H1009671:
For these two examples, I need 3SA70000SUPPL from the first and H1009671 from the second. How would I do this using SQL? I have heard that case statements might work, but I don't see how. Please help.
This works in Oracle 11g:
with tbl as (
select ':000000000:370765:P:000001359:::3SA70000SUPPL:3SA70000SUPPL:' str from dual
union
select ':000000000:715186816:P:000001996:::H1009671:H1009671:' str from dual
)
select REGEXP_SUBSTR(str, '([^:]*)(:|$)', 1, 8, NULL, 1) data
from tbl;
Which can be described as "look at the 8th occurrence of zero or more non-colon characters that are followed by a colon or the end of the line, and return the 1st subgroup (which is the data less the colon or end of the line).
From this post: REGEX to select nth value from a list, allowing for nulls
Sorry, just saw you are using DB2. I don't know if there is an equivalent regular expression function, but maybe it will still help.
For the fun of it: SQL Fiddle
first substring gets the string at ::: and second substring retrieves the string starting from ::: to :
declare #x varchar(1024)=':000000000:715186816:P:000001996:::H1009671:H1009671:'
declare #temp varchar(1024)= SUBSTRING(#x,patindex('%:::%', #x)+3, len(#x))
SELECT SUBSTRING( #temp, 0,CHARINDEX(':', #temp, 0))

How to get rightmost 10 places of a string in oracle

I am trying to fetch an id from an oracle table. It's something like TN0001234567890345. What I want is to sort the values according to the right most 10 positions (e.g. 4567890345). I am using Oracle 11g. Is there any function to cut the rightmost 10 places in Oracle SQL?
You can use SUBSTR function as:
select substr('TN0001234567890345',-10) from dual;
Output:
4567890345
codaddict's solution works if your string is known to be at least as long as the length it is to be trimmed to. However, if you could have shorter strings (e.g. trimming to last 10 characters and one of the strings to trim is 'abc') this returns null which is likely not what you want.
Thus, here's the slightly modified version that will take rightmost 10 characters regardless of length as long as they are present:
select substr(colName, -least(length(colName), 10)) from tableName;
Another way of doing it though more tedious. Use the REVERSE and SUBSTR functions as indicated below:
SELECT REVERSE(SUBSTR(REVERSE('TN0001234567890345'), 1, 10)) FROM DUAL;
The first REVERSE function will return the string 5430987654321000NT.
The SUBSTR function will read our new string 5430987654321000NT from the first character to the tenth character which will return 5430987654.
The last REVERSE function will return our original string minus the first 8 characters i.e. 4567890345
SQL> SELECT SUBSTR('00000000123456789', -10) FROM DUAL;
Result: 0123456789
Yeah this is an old post, but it popped up in the list due to someone editing it for some reason and I was appalled that a regular expression solution was not included! So here's a solution using regex_substr in the order by clause just for an exercise in futility. The regex looks at the last 10 characters in the string:
with tbl(str) as (
select 'TN0001239567890345' from dual union
select 'TN0001234567890345' from dual
)
select str
from tbl
order by to_number(regexp_substr(str, '.{10}$'));
An assumption is made that the ID part of the string is at least 10 digits.