Is there any option to check whether data “IS NUMERIC” in a DB2 table?
We want to examine CHAR data but return only those where the entire data consists only of numbers. For example, can we write a query like this?
SELECT * FROM TABLENAME WHERE VAR IS NUMERIC.
The VAR variable is defined as a CHAR(5) column and it will contain data like below.
Out of the above 5 records we would want only the 3rd and 4th records to be returned. We tried CAST (VAR as integer), but any other option is there for fetching like above. Please explain
Well, if you try to cast non-numeric data to numeric you will get an error. But you can test the data beforehand – digit by digit – using the SUBSTR function. You’d have to break the VAR column down using SUBSTR to get each individual character and test whether that character is between 0 and 9 – then only if all characters are between 0 and 9 would the result be returned.
Here is what the SQL might look like:
SELECT * FROM TABLENAME WHERE SUBSTRING(VAR,1,1) BETWEEN '0' AND '9' AND SUBSTRING(VAR,2,1) BETWEEN '0' AND '9' AND SUBSTRING(VAR,3,1) BETWEEN '0' AND '9' AND SUBSTRING(VAR,4,1) BETWEEN '0' AND '9' AND SUBSTRING(VAR,5,1) BETWEEN '0' AND '9';
This will return only those rows where every digit in the VAR column is a number between zero and nine. Of course, there are alternate queries that can also work, such as:
SELECT * FROM TABLENAME WHERE TRANSLATE(VAR, ' ', '0123456789,. ') = '' AND VAR <> '';
SELECT * FROM TABLENAME WHERE VAR like '[0-9][0-9][0-9][0-9][0-9]';
Choose one that works the best for you and away you go!
This post was originally posted on Craig Mullins’ blog at http://db2portal.blogspot.com.
EPM applications help measure the business performance. This post will help you choose the best EPM solutions for your organization’s needs and objectives.
It’s 2015 and you can now establish totally respectable MS SQL DBA credibility just by mentioning you have been in the game since SQL Server version 9. You may even get the same gasps of shock from some colleagues that used to be reserved for the version 6 veterans.