[Last Call] Learn about multicloud storage options and how to improve your company's cloud strategy. Register Now

x
Solved

# (SQL)How to remove leading zeros

Posted on 2016-10-13
Medium Priority
60 Views
Hi guys,
I using this query to get only digits from the [message]...
How to remove leading zeros as well?

``````SELECT LEFT(subsrt, PATINDEX('%[^0-9]%', subsrt + 't') - 1)
FROM (
SELECT subsrt = SUBSTRING([message], pos, LEN([message]))
FROM (
SELECT [message], pos = PATINDEX('%[0-9]%', [message])
FROM Table
) d
) t
``````

Thank You
table of results:
0000000000043559446
0000000000043559481
0000000000043559509
0000000000043559605
0000000000043559622
0000000000043559721
0
Question by:Darius
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points

LVL 66

Accepted Solution

Jim Horn earned 1000 total points
ID: 41842686
<Knee-jerk answer> CAST the value as an integer, which by definition all numeric data types do not support leading zeros.
0

LVL 20

Assisted Solution

Russ Suter earned 1000 total points
ID: 41842687
Quickest way I can think of is to cast it to a number and back to a string like this:

SELECT CAST(CAST('00000123' AS NUMERIC) AS VARCHAR)
0

Author Comment

ID: 41842751
Guys, thank you
0

LVL 49

Expert Comment

ID: 41843062
Just as an alternative that does not require type conversion::
``````SELECT
*
from (
select '0000000000043559446' as message
) your_table
outer apply (
select SUBSTRING([message], PATINDEX('%[^0]%', message + '0'), LEN([message])) substr
) oa
``````
That example would produce:
``````message             substr
------------------- --------
0000000000043559446 43559446
``````
1

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In part one, we reviewed the prerequisites required for installing SQL Server vNext. In this part we will explore how to install Microsoft's SQL Server on Ubuntu 16.04.
An alternative to the "For XML" way of pivoting and concatenating result sets into strings, and an easy introduction to "common table expressions" (CTEs). Being someone who is always looking for alternatives to "work your data", I came across this …
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.
###### Suggested Courses
Course of the Month13 days, 8 hours left to enroll