DB2 TRIM 000000 to 0 - sql

I have looked at:
DB2 SQL Query Trim inside trim
Trimming Blank Spaces in Char Column in DB2
SQL Trim after final semi colon
The IBM infocenter.
I have a column that is six long and a character column. A typical value would be AA01AA. I need to substring the middle 2 characters out of the value and convert to a number.
I am doing this with the following code: TRIM(L '0' FROM(SUBSTRING(Myfield, 3, 2))). In the example value above that gives me 1. The problem comes in when the value is 000000. The trim returns ''. I need it to return 0.
I have tried REPLACE(TRIM(L '0' FROM(SUBSTRING(Myfield, 3, 2))),'' ,'0') but that simply gives me a blank string back. I have also tried TRANSLATE(TRIM(L '0' FROM(SUBSTRING(Myfield, 3, 2))), '0', '') but that gives an error about parameter 03 being an invalid data type, length etc.
I would appreciate any help.

Something like this should do the trick:
integer(substr(myField,3,2)))
The SUBSTR extracts the two characters, the INTEGER takes it as input and converts it to a number. TRIM is not necessary at all.
values(integer(substr('000000',3,2)))
1
-----------
0
1 record(s) selected.

Related

How to handle string with only space in oracle sql?

I have a case where I am getting the data from DB and converting the string to a number using TO_NUMBER, but this case fails when the string is an empty string with unknown or space char like
columnA
------
4444
333333
The string '4444' and '333333' is converted to number by there is and error "ora-01722 invalid number" for the 2nd string.
Can this be handled with DECODE or CAST in any way, because I need to use TO_NUMBER any how for further processing?
I hope this could be Insight of your issue.
select
TO_NUMBER(trim(colA)),
TO_NUMBER(REGEXP_REPLACE(colA,'(^[[:space:]]*|[[:space:]]*$)')),
regexp_instr(colA, '[0-9.]')
from
(
select ' 123' colA from dual
union all
select ' ' colA from dual
union all
select '.456' colA from dual
)
This is similar issue : Trim Whitespaces (New Line and Tab space) in a String in Oracle
If all the data within that column is composed of integers, integers with leading and/or trailing whitespaces, null values and only whitespaces then only using TRIM() function will suffice such as
SELECT TRIM(columnA)
FROM t
and that would be more performant than using functions of regular expressions
But
If the data contains decimal numbers, letters, punctiations and special characters along with whitespaces and null values, then use
SELECT TRIM('.' FROM REGEXP_REPLACE(columnA,'[^[:digit:].]'))
FROM t
where there is at most one dot character assumed to be between the starting and ending digits. All of the leading and trailing dots are trimmed at the end of the operation provided there is any of them. The other characters are already removed by the regular expression.
If you're sure that there's no trailing or leading dots, then using
SELECT REGEXP_REPLACE(columnA,'[^[:digit:].]')
FROM t
would be enough
Demo
You can wrap up any of the expressions with TO_NUMBER() function depending on your case at the end

SQL Server substring without upper bound

What is the best way in SQL Server to do
SELECT
SUBSTRING('CATCH ME IF YOU CAN', 2, 10000)
-- ATCH ME IF YOU CAN
with no upper bound?
Use STUFF instead (STUFF (Transact-SQL)):
SELECT STUFF('CATCH ME IF YOU CAN',1,1,'');
Here, STUFF replaces 1 character, from position 1 with the string ''. The 2nd parameter is the start position, and the 3rd is the number of characters (from that position) to replace. The 4th is the replacement string.
So, as a further example, you could do something like this:
SELECT STUFF('2019-07-09 11:38:00',11,1,'T');
This replaces 1 character from position 11 with the character 'T', which returns '2019-07-09T11:38:00', changing the above value to the ISO8601 format. As you can see, the length of the string to replace does not need to be the same length as the replacement string as well (in fact, the 3rd parameter can have a value of 0, meaning that no characters are replaced and the "replacement" string is simply injected into the existing value).
Using LEN() with variable
DECLARE #Val AS VARCHAR (MAX) = 'CATCH ME IF YOU CAN';
SELECT SUBSTRING(#Val, 2, LEN(#Val));
or directly with LEN()
SELECT SUBSTRING('CATCH ME IF YOU CAN', 2, LEN('CATCH ME IF YOU CAN'));
You can use RIGHT() function, combined with LEN().
All you have to do is subtract from LEN() the number of chars that you want to exclude from the start of the string:
SELECT RIGHT('CATCH ME IF YOU CAN', LEN('CATCH ME IF YOU CAN') - 1)

In db2 how to select a column in integer having aligned it to right with leading spaces?

I need to extract a report from some tables using db2 having pgm(dnatiaul).
Using a query i want to get the below output with first char to be spaces.
ex: integer(16)
54457750
49457750
o/p: char(int(16))
54457750
49457750
As i am trying to convert it to char it is aligning to left.
I tried Lpad which gives me **extra length i.e (18) + '.' also
Help me
LPAD is the right choice, but you would need to specify how long the result string needs to be. This can be done using CAST. Here I cast the result to 10 characters.
db2 "select cast(lpad(123422,10,' ') as char(10)) as testme from sysibm.sysdummy1"
TESTME
----------
123422
1 record(s) selected.
DIGITS(integer_column_name) will give you a character string of CHAR(10) with the numeric value right-justified and left-filled with zeroes. Thus, an integer column containing 543210 will become a character string containing 0000543210.
Likewise, DIGITS(small_integer_column_name) will give you a character string of CHAR(5)

Regex to split values in PostgreSQL

I have a list of values coming from a PGSQL database that looks something like this:
198
199
1S
2
20
997
998
999
C1
C10
A
I'm looking to parse this field a bit into individual components, which I assume would take two regexp_replace function uses in my SQL. Essentially, any non-numeric character that appears before numeric ones needs to be returned for one column, and the other column would show all non-numeric characters appearing AFTER numeric ones.
The above list would then be split into this layout as the result from PG:
I have created a function that strips out the non-numeric characters (the last column) and casts it as an Integer, but I can't figure out the regex to return the string values prior to the number, or those found after the number.
All I could come up with so far, with my next to non-existant regex knowledge, was this: regexp_replace(fieldname, '[^A-Z]+', '', 'g'), which just strips out anything not A-Z, but I can;t get to to work with strings before numeric values, or after them.
For extracting the characters before the digits:
regexp_replace(fieldname, '\d.*$', '')
For extracting the characters after the digits:
regexp_replace(fieldname, '^([^\d]*\d*)', '')
Note that:
if there are no digits, the first will return the original value and then second an empty string. This way you are sure that the concatenation is equal to the original value in this case also.
the concatenation of the three parts will not return the original if there are non-numerical characters surrounded by digits: those will be lost.
This also works for any non-alphanumeric characters like #, [, ! ...etc.
Final SQL
select
fieldname as original,
regexp_replace(fieldname, '\d.*$', '') as before_s,
regexp_replace(fieldname, '^([^\d]*\d*)', '') as after_s,
cast(nullif(regexp_replace(fieldname, '[^\d]', '', 'g'), '') as integer) as number
from mytable;
See fiddle.
This answer relies on information you delivered, which is
Essentially, any non-numeric character that appears before numeric
ones needs to be returned for one column, and the other column would
show all non-numeric characters appearing AFTER numeric ones.
Everything non-numeric before a numeric value into 1 column
Everything non-numeric after a numeric value into 2 column
So there's assumption that you have a value that has a numeric value in it.
select
val,
regexp_matches(val,'([a-zA-Z]*)\d+') AS before_numeric,
regexp_matches(val,'\d+([a-zA-Z]*)') AS after_numeric
from
val;
Attached SQLFiddle for a preview.

zero padding in teradata sql

Table A
Id varchar(30)
I'm trying to re-create a logic where I have to use 9 digit Ids irrespective of the actual length of the Value of the Id field.
So for instance, if the Id is of length 6, I'll need to left pad with 3 leading zeros. The actual length can be anything ranging from 1 to 9.
Any ideas how to implement this in Teradata SQL?
If the actual length is 1 to 9 characters why is the column defined as VarCar(30)?
If it was a numeric column it would be easy:
CAST(CAST(numeric_col AS FORMAT '9(9)') AS CHAR(9))
For strings there's no FORMAT like that, but depending on your release you might have an LPAD function:
LPAD(string_col, 9, '0')
Otherwise it's:
SUBSTRING('000000000' FROM CHAR_LENGTH(string_col)+1) || string_col,
If there are more than nine characters all previous calculations will return them.
If you want to truncate (or a CHAR instead of a VARCHAR result) you have to add a final CAST AS CHAR(9)
And finally, if there are leading or trailing blanks you might want to use TRIM(string_col)