Trim Leading Zeroes Only If Numeric - sql

I have a column containing a combination of numeric and alphanumeric values. When the value is strictly numeric, the database stores it with leading zeroes (but not always), but not if not.
Here's some sample data:
I need to use these values as part of a string that I will use to join to another table. Unfortunately, the portion of the string that corresponds to this field in the other table snips off the leading zeroes of any of the numeric-only values. I'm stumped finding a method of snipping the leading zeroes ONLY in this case.
I found this solution, but it's not for SQL Server (2012). Trim leading zeroes if it is numeric and not trim zeroes if it is alphanumeric
I also saw this, but it also removes the leading zeroes from the hyphenated values shown in the example, which doesn't work. Better techniques for trimming leading zeros in SQL Server?
Help! Thanks!

You could use:
select (case when col not like '%[^0-9]%'
then convert(varchar(255), try_convert(numeric(38), col))
else col
end)
This works for up to 38 digits after the leading zeros

The database does not store anything in varchar (text) fields except what you give it. If you give it leading zeroes, it will save them, it has no reason not to as it's just a piece of text.
For your problem, you can do this:
ISNULL(CAST(TRY_CAST(field AS numeric(38)) AS varchar(insert_field_length))), field)

Related

Select column ignore beginning numbers

I have a column that I need to select but it has an inconsistent amount of numbers/formatting in the beginning
The column values are ideally supposed to be structured like:
# Question_-_Answer
But here are some examples which make it hard to remove the numbers in the beginning
0 Question1_-_50-60
1.Question_-_apple
12Question_-_40/50
13 Question_-_orange
14.Question_-_apple
15. Question_-_orange2
Is there a way I can query this column so that it ignores everything until the first alphabetical character while also not removing any characters/alphanumerical values in the question and answer portion?
You can use PATINDEX and STUFF to achieve this:
SELECT STUFF(V.YourString,1,PATINDEX('%[A-z]%',V.YourString)-1,'')
FROM (VALUES('0 Question1_-_50-60'),
('1.Question_-_apple'),
('12Question_-_40/50'),
('13 Question_-_orange'),
('14.Question_-_apple'),
('15. Question_-_orange2'))V(YourString);
This removes all characters up to the first alpha character.

How to search by SQL while doing "a cut of trailing zeros" on a number field?

I have a db table in oracle where I have a column defined as a number.
The columns contains numbers like:
MyColumn
12540000000
78590000000
I want to find the records by searching MyColumn=12540000000 as well as MyColumn=1254 (without trailing zeros).
What could I try? TO_CHAR and a cutting logic or is there something more simple?
rtrim(MyColumn, '0') = '1254'
Note that on the right I enclosed the string within quotes (so it is really seen as a string, not a number). Apparently you are treating these as strings, right? Even if MyColumn is a number, it will be implicitly converted to a string before applying rtrim.

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.

preserv leading zeros fetched in SQL at excel

i have SQL query which fetches item details from table, this SQL include lot number as a field, i have noticed that when i run the query few rows have either leading zeros or text look like 51E03 when i export to excel, leading zeros will go off 00021 became 21 and 51E03 will converted 51000, is it possible to retain the values as is when it get copy with headers from SSMS?
You can preserve leading zeros by prepending the numeric values with a single quote. Well, actually, if they have leading zeros, then they are really character strings. So, something like this:
select '''' + AccountNumber
from table t;

SQL Float to Varchar

This is actually a (not very elegant) solution to a problem I had trying to return a float in to a varchar column when doing a union from a dummy_table with some fudged data totals.
In order to get the float to a string, I used the following function in SQL server 2008 (which I found on SO):
str(sum(<float_column>),25,5)
This left lots of leading spaces and trailing zeroes, which was undesirable.
I used the following strings to test the formatting with a dummy table (note that there are 24 preceding spaces that don't show):
' 8.50000'
' 0.50000'
' 8.00000'
I used the following functions to get the desired format:
select replace(rtrim(replace(replace(rtrim(replace(ltrim(
' 8.0000'),'0',' ')),' ','0'),'.',' ')),' ','.') from dummy_table;
This works in the following order:
LTRIM trims empty space to the left.
Replace all zeroes with empty spaces.
RTRIM trims these empty spaces from the right.
Replace all spaces with zeroes.
Replace the dot with space.
Trim all space from the right (to get rid of trailing dot if exists).
Replace spaces with dots (to put dot in the correct place if exists).
If you guys can think of a nicer way to do it, let me know!
round should work for this.
select round(8.5000000000,5)
http://sqlfiddle.com/#!3/1fa93/8845