DB2 SQL Convert Decimal to Character with Padded Zeros - sql

How can I convert my DECIMAL(11) field from 12345678 to a character value of 00012345678?

Only use the DIGITS function, because this verifies the length of the field numeric or decimal, etc and completes with zeros to the left when is necessary.
SELECT DIGITS(FIELD) FROM ...
The length of the resulting string is always:
5 if the argument is a small integer
10 if the argument is a large integer
19 if the argument is a big integer

Based on your comment in #Mr Fuzzy Botton's answer, I'm guessing you're on DB2 for i, which does not have the LPAD function. You could instead use a combination of the REPEAT and RIGHTfunctions:
SELECT RIGHT(REPEAT('0', 11) || LTRIM(CHAR(your_field)), 11)
FROM your_table

Using http://pic.dhe.ibm.com/infocenter/dzichelp/v2r2/topic/com.ibm.db2.doc.sqlref/castsp.htm for details on CAST
and http://pic.dhe.ibm.com/infocenter/dzichelp/v2r2/topic/com.ibm.db2z10.doc.sqlref/src/tpc/db2z_scalarfunctionsintro.htm for string functions,
I assume this should do the trick -
SELECT LPAD( CAST(FIELD AS CHAR(11)) ,11,'0') AS PADDEDFIELD

Don't know if you've worked it out, however try this:
SELECT LPAD( DIGITS( fieldName ), 11, '0') ) as paddedFieldName FROM yourTable
The LPAD is the left padding, but the DIGITS function was the only way I got DB2 to treat the numeric value like a string.

My LeftPad function without LeftPad function
REPEAT('0', 4-length(MY_COLUMN_VALUE))||CHAR(MY_COLUMN_VALUE) as NEW_COLUMN
MY_COLUMN_VALUE NEW_COLUMN
1 0004
23 0023
testing ...
SELECT '32' MY_VALUE, REPEAT('0', 4-length('23'))||CHAR('23') as LEFTPAB_MY_VALUE FROM sysibm.sysdummy1

If this is DB2 for i, and myColumn data type is DECIMAL with precision (11) and scale (0), then:
SELECT digits( myColumn ) FROM sysibm.sysdummy1
will return:
....+....1.
DIGITS
00001234567
Changing the number of leading zeros could be done in many ways. CASTing to a different precision before using DIGITS() is one way.

SELECT SUBSTRING(
CHAR(100000000000+fieldName),
2,11
) as paddedFieldName
FROM yourTable
I only wanted to define my field once in the select statement so the above worked for me and is tidy

I just went the other direction: cast(field as int)

Try this for your field x:
substr(digits(x), 33 - length(x), length(x) )

From Numeric 8,0 (datenumfld=20170101) to 01/01/2017 This works for me:
DATE(TO_DATE(CHAR(datenumfld), 'YYYYMMDD')) as YourDate

Related

How to remove trailing zeros after decimal points from number column in sqlplus?

I have a one database table field called Amount which type is number(38,8), and in sqlplus I have formatted the column like "COLUMN Amount FORMAT 999999999999999999999999.99999",but while writing into csv we are getting always trialing zeros.
e.g if number is 9.23 then result is will be 9.2300
e.g if number is 9 then result is will be 9.0000
How to remove trailing zeros.
Please help me..
You can do it with to_char and the format-code TM (see documentation)
SELECT to_char(column, 'TM') FROM table;
examples:
SELECT to_char(9.2300, 'TM') FROM dual; -- returns 9.23
SELECT to_char(9.0000, 'TM') FROM dual; -- returns 9
SELECT to_char(100, 'TM') FROM dual; -- returns 100
SELECT to_char(010, 'TM') FROM dual; -- returns 10
edit:
With
SELECT round(to_char(column, 'TM'), 5) FROM table;
you can limit your result to 5 decimal places.
SELECT to_char(round(123.654321000, 5), 'TM') FROM dual; -- returns 123.65432
TO_NUMBER function also removes the zeroes after decimal point.
eg : 1.4500 to 1.45, 1.9000 to 1.9 etc.
Sample Query :
SELECT TO_NUMBER(column_name) FROM table_name;
Try this.
select rtrim(rtrim(to_char(column_name), 0 ), '.' ) from table_name;

How to round a number including least significant zeros?

I am trying to execute following SQL query in Oracle
Select round ( 123.50000065 , 4 ) from dual;
Output : 123.5
Required output: 123.5000
Any help is appreciated. ..
You probably want to use to_char with required format:
Below rounds the value to 4 decimal places and formats into the required string:
Select to_char(123.50000065, '999999999990D9999') x from dual;
If you don't want to actually round the number i.e. you just want to truncate after 4 digits, use:
Select to_char(trunc(123.50000065, 4), '999999999990D9999') x from dual;
ROUND ( numeric_expression , length [ ,function ] )
SELECT ROUND(123.9994, 3), ROUND(123.9995, 3);
Output:
123.9990 124.0000
Instead of round(), use to_char() or cast() to a decimal type:
select to_char(val, '999.9999'),
cast(val as decimal(10, 4))
To control the format a number is showed, you can cast it to a string, by applying the right format mask.
Depending on how you need round your input value, one of these could be useful:
with test(x) as (
select 123.50000065 from dual union all
select 123.00004 from dual union all
select 123.00005 from dual union all
select 123.00008 from dual
)
select x,
to_char(x, 'FM99999999.0000'),
to_char(trunc(x, 4), 'FM99999999.0000')
from test ;
result:
X TO_CHAR(X,'FM9 TO_CHAR(TRUNC(
-------------------------- -------------- --------------
123,50000065000 123.5000 123.5000
123,00004000000 123.0000 123.0000
123,00005000000 123.0001 123.0000
123,00008000000 123.0001 123.0000
"Rounding" is a mathematical concept. The value (with your sample input) is 123.5. Mathematically 123.5000 is the same thing as 123.5. They are only different as STRINGS.
One way to display 123.5 as 123.5000 is to wrap round() within to_char(). However, this means you are not able to use it in further computations (actually Oracle will allow you to - it will do an implicit conversion back to number instead of throwing a data type mismatch error, as it should do).
The better way, in most cases, is to address formatting in your client software, like SQL Developer, SQL*Plus, or Toad. Here is how you can do it in SQL*Plus:
SQL> Select round ( 123.50000065 , 4 ) as result from dual;
RESULT
----------
123.5
-- change the format of the numeric column "result"
SQL> column result format 999.0000
SQL> Select round ( 123.50000065 , 4 ) as result from dual;
RESULT
---------
123.5000
I can't see how you got 123.5 from your query. mine results 123.50000000
if I understand correctly, you want your number 4 significant decimal places.
why not try cast
select cast(123.50000065 as numeric(38,4))
output: 123.5000
testing if it rounds off number:
select cast(123.50000065 as numeric(38,6))
output: 123.500001

How to format % and in 2 decimal points?

How do I code format the return data in 2 decimals and with percentage format like 100.00% or 67.39% instead of 100.000000 or 67.391304?
SUM(qa.scripting1+qa.conduct1+qa.conduct2+qa.conduct3)*100.0/46 as 'C%'
I tried ROUND() but I got the error stating that the round function requires 2 to 3 arguments?
ROUND(SUM(qa.scripting1+qa.conduct1+qa.conduct2+qa.conduct3)*100.0/46) as 'C%'
Thanks!
You can convert to a decimal your original value:
CONVERT(VARCHAR(20), CONVERT(DECIMAL(18,2), SUM(qa.scripting1+qa.conduct1+qa.conduct2+qa.conduct3)*100.0/46) ) + '%' as 'C%'
The first number in the decimal represents the number of digits in the number including decimal places, and the second number represents the number of decimal places.
You should pass number of decimals in second parameter to round function. For formating you can cast number to money and then cast to varchar:
select cast(cast(ROUND(SUM(123.12321)*100.0/46, 2) as money) as varchar) + '%'
Using Round and Cast will work. First round to 2 decimal places then convert to a decimal with 2 places to truncate the excess zeros.
select cast(Round(yourValue, 2) as decimal(18,2))
Sql Fiddle
You can use Format function
select FORMAT(100.0000, 'N' , 'en-us')
returns 100.00
and
select FORMAT(67.391304, 'N' , 'en-us')
returns 67.39
EDIT
In version below 2012 you can do this
SELECT CAST(67.391304 AS NUMERIC(10, 2))
returns 67.39
You can just do:
select FORMAT(0.391304, '##0.00%')
But keep in mind that it implicitly multiplies by 100, so the above will display as 39.13%.

Problem with max() in sql server

I have alphanumeric values like. XYZ1,XYZ2......XYZ11, XYZ12 and so on, now I want to select only the Max numeric value, i.e. 12 here.
I tried-
select max(REPLACE(ID,'XYZ','')) from myTable;
but this is returning 9. why?
Try converting to INT before max
select max(cast(REPLACE(ID,'XYZ','') as int)) from myTable;
It's still treating your value as a string instead of a number. Try:
select max(CAST(REPLACE(ID,'XYZ','') AS INT) from myTable;
Because you're still comparing strings. The fact that they contain only numeric digits doesn't mean that they're not strings. You need to convert them:
SELECT MAX(CAST(REPLACE(id, 'XYZ', '') AS INT)) FROM My_Table
Another method is
select max(REPLACE(ID,'XYZ','')*1) from myTable

SQL IsNumeric Returns True but SQL Reports 'Conversion Failed'

Assuming the following data:
Column1 (data type: varchar(50))
--------
11.6
-1
1,000
10"
Non-Numeric String
I have a query, which is pulling data from this column and would like to determine if the value is a number, then return it as such in my query. So I am doing the following
SELECT CASE
WHEN IsNumeric(Replace(Column1, '"', '')) = 1 THEN Replace(Column1, '"', '')
ELSE 0
END AS NumericValue
SQL is reporting back:
Conversion failed when converting the varchar value '11.6' to data type int.
Why? I have also tried to force cast this:
SELECT CASE
WHEN IsNumeric(Replace(Column1, '"', '')) = 1 THEN cast(Replace(Column1, '"', '') AS float)
ELSE 0
END AS NumericValue
And I got:
Error converting data type varchar to float.
You need to replace comma with a period:
CAST(REPLACE(column, ',', '.') AS FLOAT)
SQL Server outputs decimal separator defined with locale, but does not unterstand anything but a period in CASTs to numeric types.
First convert the string to money, then covert it to any other numeric format since money type gives a true numeric string always. You will never see an error then.
Try the following in your query, and you'll know what I am talking about. Both will return 2345.5656. The Money datatype is rounded to 4 decimal places, and hence the casting causes rounding to 4 decimal places.
SELECT CAST('2,345.56556' as money), CAST('$2,345.56556' as money)
Cast( cast('2,344' as money) as float) will work perfectly or
cast( cast('2,344' as money) as decimal(7,2)) will also work.
Even cast(CAST('$2,345.56556' as money) as int ) will work perfectly rounding it to nearest integer.
There are many issues with SQL isnumeric. For example:
select isnumeric('1e5')
This will return 1 but in many languages if you try to convert it to a number it will fail. A better approach is to create your own user defined function with the parameters you need to check for:
http://www.tek-tips.com/faqs.cfm?fid=6423
ISNUMERIC returns 1 when the input expression evaluates to a valid integer, floating point number, money or decimal type;
So the problem is it is a valid number but not a valid int.
Kyle,
I think this solves the problem. The problem lies in the fact that the ELSE clause initializes your result to be an INTEGER. By making an explicit typecast to FLOAT and adding the suggestion of Quassnoi, it seems to work.
DECLARE #MyTable TABLE (Column1 VARCHAR(50))
INSERT INTO #MyTable VALUES('11.6')
INSERT INTO #MyTable VALUES('-1')
INSERT INTO #MyTable VALUES('1,000')
INSERT INTO #MyTable VALUES('10" ')
INSERT INTO #MyTable VALUES('Non-Numeric String')
SELECT CASE WHEN ISNUMERIC(REPLACE(Column1,'"','')) = 1 THEN REPLACE(REPLACE(Column1,'"',''), ',', '.') ELSE CAST(0 AS FLOAT) END
FROM #MyTable
Regards,
Lieven
IsNumeric(' ') also returns 1, but then CAST as int blows up. Brendan above says write your own function. He is correct.
This solution does not work in all cases (specifically numbers with money and/or thousand separators). Concatenate an exponent representation to the end of the number which is represented by a string...ISNUMERIC() works fine from there. Examples below:
-- CURRENT ISNUMERIC RESULTS
SELECT ISNUMERIC('11.6'); --1
SELECT ISNUMERIC ('-1'); --1
SELECT ISNUMERIC('1,000'); --1
SELECT ISNUMERIC('10"'); --0
SELECT ISNUMERIC('$10'); --1
-- NEW ISNUMERIC RESULTS
SELECT ISNUMERIC('11.6'+'e+00'); --1
SELECT ISNUMERIC ('-1'+'e+00'); --1
SELECT ISNUMERIC('1,000'+'e+00'); --0
SELECT ISNUMERIC('10"'+'e+00'); --0
SELECT ISNUMERIC('$10'+'e+00'); --0
This, at the very least, standardizes the format for using the REPLACE() function.
I have just meet this issue.
You can try this solution if you don't mind about limitation of decimal length.
CONVERT(numeric, CONVERT(money, '.'))
NOTE:
It is supported in SQL Server 2008 or above.
Money range is : -922,337,203,685,477.5808 to 922,337,203,685,477.5807 - four decimals.