Conversion of varchar to number - sql

I have a question that bothers me. How can i convert a varchar to number when inside the varchar value consists of alphabets.
For my varchar price column values:
14dollars10cents
15dollars20cents
By converting it to varchar to number price column, the values should be:
1410
1520
I know that if the varchar does not consists any alphabets, it can auto convert by"
SELECT CONVERT(INT, PRICE) FROM Table
Is there any way to get rid of the alphabets in the middle as I would like to do mathematical function on it.
Updated attempt of putting fixed point number in:
SELECT CAST (Replace(REPLACE(PRICE, 'dollars', '.'),'cents','') AS Number(4,2)))
FROM TEST;
Thanks

You could just use REGEXP_REPLACE to remove all non digit characters:
SELECT REGEXP_REPLACE(price, '[^[:digit:]]')
FROM table;
To then convert this to a number:
SELECT TO_NUMBER(REGEXP_REPLACE(price, '[^[:digit:]]'))
FROM table;
If you want to add the point in then you can do that with REGEXP_REPLACE too:
SELECT TO_NUMBER(REGEXP_REPLACE(val, '^([0-9]*)([^[:digit:]]*)([0-9]*)(.*)$', '\1.\3'))
FROM table;
Voila...

SELECT CAST(REPLACE(YourVarcharCol, 'dollars', '') AS INT) FROM Table
The issue with this is it will break if the varchar still contains alpha-numeric characters.

How about using translate to strip out the unwanted characters.
SELECT TO_NUMBER(TRANSLATE('14dollars10cents','1234567890dolarscents','1234567890')) FROM DUAL

No I don't think there is direct way.
you can do string parsing to get your integer value.

Related

How to remove trailing zeroes in snowflake?

I have a column that is in INT type. I want to remove all the trailing zeroes and only have the number. The example below, should follow be: 3,10,20,20. I cannot have the 4 zeroes at the end.
Is there a way to do this?
You could try casting your numeric data to integer, e.g.
SELECT AS_INTEGER(col) AS col
FROM yourTable;
the 3dp is how floating point numbers print, thus you can cast to number SELECT column_name::number FROM table
If your data is a string/varient type, and not all values stored in your column always casts cleanly, in Snowflake you can hit error, with the TO_NUMBER or ::number forms, thus [TRY_TO_NUMBER][2] form should be used.

REPLACE WITH NVL

select to_number(replace(nvl('-100,000',0),'',','),'999,999,999.99')from dual;
... produces the output: 100000
Now I use the same expression in my procedure with table column:
select to_number(replace(nvl(TABLEA.VOLUME,0),'',','),'999,999,999.99')from TABLEA;
... and get the output: INVALID NUMBER
Column VOLUME in TABLEA is of type VARCHAR2.
Most certainly the contents of column VOLUME are stored as strings without the grouping character ( , ). Thus the strings violate the format in the conversion with to_number.
In addition, the argument order in REPLACE makes no sense.
Finally, you want to swap the calls to NVL and REPLACE.
So - assuming that you want to parse numbers with 2 fractional digits given as strings - use the following:
select to_number ( nvl ( replace (TABLEA.VOLUME, ',', ''), 0), '999999999.99') from TABLEA;
Seems you want to convert the string values to money format.
First, consider replace as you did by switching '' and ',' parameters in the argument order to remove the commas, and making suitable for numeric conversion as :
to_number(replace(nvl(str,0),',','')),
and then apply the money format as :
with tableA as
(
select '-100,000' as volume
from dual
)
select to_char(
to_number(replace(nvl(volume,0),',',''))
,'fm999G999G990D00','NLS_NUMERIC_CHARACTERS = ''.,''')
as Money
from tableA;
MONEY
-----------
-100,000.00
Depending on the currency displaying style the order of dot and comma can be switched as
'NLS_NUMERIC_CHARACTERS = '',.''' to display the money as -100.000,00.
P.S. first of all, you need to make sure all the data for volume column can be casted to number to be able to use to_number() conversion.
Demo

Leading Zeros getting truncated using SUBSTRING

One of the values in the column is
089-002007
I wish to extract all the numbers after '-'
SELECT SUBSTR(EMP_NO,5)
FROM Table_Name
However, I get the output as '2007', the leading zeros got truncated. I have multiple values where it starts with 0 after the '-'.
how can I fix this?
Looks like it's implicitly changing the result to int, hence chopping off leading zeroes. I would suggest CAST-ing the SELECT
SELECT CAST(SUBSTR(EMP_NO,5) AS VARCHAR(10))
FROM Table_Name
What platform and version of DB2?
You should be getting '002007' back given the code you've shown.
The output of SUBSTR() is already varchar.
The DBMS wouldn't change it from varchar to int, unless you've tried to treat it like an int.
select substr('089-002007',5)
from sysibm.sysdummy1
Returns
SUBSTR
002007
On the other hand,
select substr('089-002007',5) + 0
from sysibm.sysdummy1
Returns
Numeric Expression
2,007

Convert INT to VARCHAR SQL

I am using Sybase and I am doing a select which returns me a column called "iftype", but its type is int and I need to convert into varchar. When I try to do the select without the convert function I get this error:
Error code 257, SQL state 37000: Implicit conversion from datatype 'VARCHAR' to 'INT' is not allowed. Use the CONVERT function to run this query.
I dont know how to implement the function CONVERT. Can anyone help me, please ?
Use the convert function.
SELECT CONVERT(varchar(10), field_name) FROM table_name
Use the STR function:
SELECT STR(field_name) FROM table_name
Arguments
float_expression
Is an expression of approximate numeric (float) data type with a decimal point.
length
Is the total length. This includes decimal point, sign, digits, and spaces. The default is 10.
decimal
Is the number of places to the right of the decimal point. decimal must be less than or equal to 16. If decimal is more than 16 then the result is truncated to sixteen places to the right of the decimal point.
source: https://msdn.microsoft.com/en-us/library/ms189527.aspx
You can use CAST function:
SELECT CAST(your_column_name AS varchar(10)) FROM your_table_name
Actually you don't need to use STR Or Convert. Just select 'xxx'+LTRIM(ColumnName) does the job.
Possibly, LTRIM uses Convert or STR under the hood.
LTRIM also removes need for providing length. It seems to be working for integer or float without worry of truncation.
SELECT LTRIM(ColumnName) FROM TableName
also, LTRIM is better than STR as
SELECT STR(1234567890.123)
gives 1234567890
whereas
SELECT LTRIM(1234567890.123)
gives 1234567890.123
SELECT Cast(Cast([field_name] AS BIGINT) AS NVARCHAR(255))
FROM table_name
CONVERT(DATA_TYPE , Your_Column) is the syntax for CONVERT method in SQL. From this convert function we can convert the data of the Column which is on the right side of the comma (,) to the data type in the left side of the comma (,) Please see below example.
SELECT CONVERT (VARCHAR(10), ColumnName) FROM TableName

numbers going from int to varchar

I have column in a postgresql database. They are lottery numbers. Four digits in length to be exact. Initially I had the datatype of the column as int. I inserted all the lottery numbers. After I inserted all the numbers I realize it chopped off my zeros. For instance 0925 is 925. I fixed the datatype to be varchar but now I need to figure out how to fix it from int to varchar with the same data. The data needs to be 4 digits in length. I was trying to just figure out how many problem numbers there are and I couldn't write a select statement that told me how many rows have less than 4 digits.
How should I go about this?
Thanks.
I was trying to just figure out how many problem numbers there are and I couldn't write a select statement that told me how many rows have less than 4 digits.
SELECT COUNT(*)
FROM lottery
WHERE char_length(x) < 4
See it working online: sqlfiddle
To fix them, you may find lpad useful. Note that the WHERE clause is not actually needed.
UPDATE lottery
SET x = lpad(x, 4, '0')
See it working online: sqlfiddle
Format your numbers with to_char():
SELECT to_char(123, 'FM0000');
You might even just leave them as integer and use the expression in queries.
Or, to convert your column back from integer to text in place:
ALTER TABLE tbl ALTER column col TYPE text USING to_char(col, 'FM0000');
Since you seem to have already converted the numbers to varchar, the expression needs an additional cast to integer:
SELECT to_char(col::int, 'FM0000')
FROM tbl;