How to convert string to numbers (if numeric), otherwise leave as string in SQL - sql

my column has customer numbers that are both numeric and combinations of text and numbers. I only want to convert them if they are all numeric otherwise leave them as a string
ex.
91036
ab321
10001
Only convert 91036 and 10001 as numbers (using cast or convert) but leave ab321 as string. I tried isnumeric but this isn't a recognized function in the query builder I'm using. And if I convert using cast or convert the strings are disappearing.

This is an example based on Oracle, but I believe that the same principle would work elsewhere (at least, in databases that support regular expressions).
I don't quite understand what you meant by saying that you want to "convert" those values to numbers; convert where? I presume that they are currently stored in a VARCHAR2 (or some other "character" datatype column). There's no use in converting them to number an leave them in the same column, as that wouldn't do absolutely anything - they would still be treated as strings (stored in the character datatype column, remember?).
So, I've created another - NUMBER datatype column and will populate it with a number whenever possible.
Sample data:
SQL> create table test (col_char varchar2(10),
2 col_num number);
Table created.
SQL> insert into test (col_char)
2 (select '91036' from dual union
3 select 'ab321' from dual union
4 select '10001' from dual
5 );
3 rows created.
Update uses REGEXP_LIKE function which checks whether COL_CHAR looks like a number:
^ anchors you to the beginning of the string
\d+ takes as many consecutive digits as it can find
$ anchors you to the end of the string
which, all together, means that string must begin with a digit, must end with a digit, and everything in between have to be digits.
SQL> update test set
2 col_num = to_number(col_char)
3 where regexp_like(col_char, '^\d+$');
2 rows updated.
SQL> select * From test;
COL_CHAR COL_NUM
---------- ----------
10001 10001
91036 91036
ab321
SQL>
Things are getting somewhat more complex when there are decimals and/or thousands separators in a string, so you might need to alter both TO_NUMBER function and regular expression pattern. For example:
SQL> update test set
2 col_num = to_number(col_char, '999990D00000', 'nls_numeric_characters = '',.''')
3 where regexp_like(col_char, '^[0-9]+|(\,)[0-9]+$');
2 rows updated.
SQL> select * from test;
COL_CHAR COL_NUM
---------- ----------
10001 10001
91,036 91,036
ab321
SQL>

Related

Netezza code to convert data ending with minus symbol and instead having it start with minus

In a table I have numbers in the format of character datatype with both minus and plus figures. The issue is the ones having minus which looks like for instance 1.000- (instead of being -1.000)
The ones that are plus is looking like 1.000 which is all fine hence only the ones supposed to be minus I need to correct.
Below code is the closest I have reached but problem is that when testing it everything becomes minus even if there are plus figures as well. It have been casted to int datatype from being character in order to be able to sum it.
cast('-' || SUBSTR(Numbers, 1, LENGTH(Numbers) - 1)as int)
So to summarize my question how can I have the character data in "Numbers" column to become -1 if its 1- and do nothing if its 1 in IBM Netezza database?
Thanks!
The to_number function in your friend in such cases
select * from test;
C1
--------
1.000-
21-
1.2
2
100-
1.23-
213.01
(7 rows)
Now we can convert it to the right text by doing
select to_number(c1, '9999D999S') from test;
TO_NUMBER
-----------
-1.000
-21.000
1.200
2.000
-100.000
-1.230
213.010
(7 rows)

Oracle to_char format mask covering 0.1 -> .1 case

So I have the following situation:
create table test1(c1 number, c2 varchar2(250 char));
/
insert into test1 values(0.11, 0.11);
/
select * from test1;
will give me:
C1 C2
0.11 .11
I want to store a number like 0.11 as it is, without removing the 0. Problem is that in that varchar2 column I can also store values like "1.123", "0.123456789", "test123". So basically it can be a number with any precision or even a string.
I think my only chance is to use the "fmt" parameter of to_char, but I can't find a mask that could solve any given number of digits and strings
You can try below using to_char() and fmt as '90D90'
create table test1(c1 number, c2 varchar2(250 char))END;
/
insert into test1 values(0.11, to_char(0.11, '90D90'))END;
/
select * from test1;
Found a solution using regex:
select regexp_replace('.11115', '^(\.\d+)$', '0\1') from dual
This searches if it starts with a dot and continues only with digits. Won't crash if you pass it a string and the precision length doesn't matter

How to add Leading Zeros in Sequence in SQL Server 2012?

I have a column in my Table i.e. TieBreaker which accepts only 4 digits Length value.
I have wrote a SQL SEQUENCE to generate a Series :
/* Snippet to DELETE Existing Sequence*/
IF EXISTS
(
SELECT * FROM Sys.Sequences WHERE Name = 'TieBreaker'
) DROP SEQUENCE TieBreaker
GO
/* Snippet to CREATE Sequence*/
CREATE SEQUENCE TieBreaker AS INT
START WITH 0000
INCREMENT BY 1
MINVALUE 0000
MAXVALUE 9999
CYCLE
GO
How can I output with Leading 0 for my sequence ? Like Below :
You do not. A number has no leading zeroes, as we all have learned in school.
The character formatting has. So you have 3 choices:
Make the field a varchar. This is not totally off as many number sequences also have prefixes and ARE NOT NUMBERS.
Add another computed field that formats the output so you can use that.
Do not care on database level but format in whatever program uses it.
An example of using a computed column for formatting
CREATE TABLE Test (
TieBreakerSeq INT DEFAULT NEXT VALUE FOR TieBreaker,
TieBreakerAsChar AS FORMAT(TieBreakerSeq, '0000#'),
SomeOtherData VARCHAR(10)
)
INSERT INTO Test (SomeOtherData) VALUES ('A'),('B'),('C')
SELECT * FROM Test
TieBreakerSeq TieBreakerAsChar SomeOtherData
------------- ---------------- -------------
0 00000 A
1 00001 B
2 00002 C
did u try
select lpad(TieBreaker.nextval,'4','0') from dual;
it would give same result right?
0000
0001
0002 and so on..

Oracle double conversion

I have this example:
CREATE TABLE test
(
VALUE NUMBER (5, 2)
);
INSERT INTO test
VALUES (6.3);
SELECT * FROM test;
In table test, I have a value of 6.3.
I have an application in .NET who queries this table and returns a single value of 6.3.
Assuming the value is stored in the s variable like this:
Dim s As Single = 6.3
Dim d As Double = CDbl(s)
.NET converts the single into a double, and the variable d has this value: 6.3000001907348633. I understand that is a different representation of the 6.3 value, but when I'm using this d value in a operation like this:
(795407.2 * d) / 100 = 50110,6551171188
in PL\SQL when I'm querying the table, I want to get the 6.3000001907348633 value instead of 6.3.
How can I convert this, or there is a datatype that does that? I've tried the BINARY_FLOAT and DOUBLE PRECISION types, but they don't convert this.
EDIT: Using 6.3 value I get: (795407.2 * d) / 100 = 50110,6536. if I round the value to get two decimal places (and assuming that this is a monetary value, I get 50110,66€ and 50110,65€ respectively).
Try using the BINARY_FLOAT Data Type in your SQL.
It represents a 32-bit floating point number in Oracle:
SQL> select cast(6.3 as BINARY_FLOAT) num,
2 to_char(cast(6.3 as BINARY_FLOAT),'0.00000000') num_to_char
3 from dual;
NUM NUM_TO_CHAR
---------- -----------
6,3E+000 6.30000019
Edit:
Sorry, I was too fast and didn't read all your trials
For compatibility purposes, try convert your number / literal to BINARY_FLOAT and then to BINARY_DOUBLE:
SQL> select TO_CHAR(cast(cast(6.3 as BINARY_FLOAT) as BINARY_DOUBLE),'0.000000000000000000') MyNum from dual;
MYNUM
---------------------
6.300000190734863300

determine DB2 text string length

I am trying to find out how to write an SQL statement that will grab fields where the string is not 12 characters long. I only want to grab the string if they are 10 characters.
What function can do this in DB2?
I figured it would be something like this, but I can't find anything on it.
select * from table where not length(fieldName, 12)
From similar question DB2 - find and compare the lentgh of the value in a table field - add RTRIM since LENGTH will return length of column definition. This should be correct:
select * from table where length(RTRIM(fieldName))=10
UPDATE 27.5.2019: maybe on older db2 versions the LENGTH function returned the length of column definition. On db2 10.5 I have tried the function and it returns data length, not column definition length:
select fieldname
, length(fieldName) len_only
, length(RTRIM(fieldName)) len_rtrim
from (values (cast('1234567890 ' as varchar(30)) ))
as tab(fieldName)
FIELDNAME LEN_ONLY LEN_RTRIM
------------------------------ ----------- -----------
1234567890 12 10
One can test this by using this term:
where length(fieldName)!=length(rtrim(fieldName))
This will grab records with strings (in the fieldName column) that are 10 characters long:
select * from table where length(fieldName)=10
Mostly we write below statement
select * from table where length(ltrim(rtrim(field)))=10;