Link to home
Start Free TrialLog in
Avatar of Becky Edwards
Becky EdwardsFlag for United States of America

asked on

How to convert number 123.8 to 1238, removing decimal, in SQL query?

How do I remove the decimal point in a string using a SQL statement?

Also, the result must result in a Char field with 7 spaces.

So 123.8 would be 1238xxx with x's being blank spaces in a fixed width file.

or D02.3 as D023xxx with x's being blank spaces always to the right of the string.

I am using SQL 2008.
ASKER CERTIFIED SOLUTION
Avatar of Brian Crowe
Brian Crowe
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Try, Replace . with '' and use RTRIM to remove spaces from the right hand side and the add SPACE(7).

Note - RTRIM is used because if we have value like '128.8 ', then we cannot add 7 spaces directly. If we add then we will get 8 spaces. So first we need trim the spaces from the right hand side and then add the 7 spaces we need.

Note - | (Appended pipe) so that we can check that there are no spaces after the string.

DECLARE @ AS VARCHAR(100) = '123.8    '

SELECT '|' + RTRIM(REPLACE(@,'.','')) + SPACE(7) + '|'

GO
DECLARE @ AS VARCHAR(100) = 'D02.3    '

SELECT '|' + RTRIM(REPLACE(@,'.','')) + SPACE(7) + '|'

Open in new window


Output

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|1238       |

(1 row(s) affected)

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|D023       |

(1 row(s) affected)


Code for you with out pipes


DECLARE @ AS VARCHAR(100) = '123.8    '

SELECT RTRIM(REPLACE(@,'.','')) + SPACE(7) 

GO
DECLARE @ AS VARCHAR(100) = 'D02.3    '

SELECT RTRIM(REPLACE(@,'.','')) + SPACE(7)

Open in new window


Hope it helps !!
Hello,

You can try this

SELECT LEFT(REPLACE(COLUMN,'.','') + '       ',7) FROM TABLE

Open in new window

Avatar of Becky Edwards

ASKER

These all worked!
  I gave the points to the first person who answered.

Thank you.
No problem :) , Thanks Becky !!

Regards,
Pawan