SQL SERVER – Removing Leading Zeros From Column in Table – Part 2

Posted by pinaldave on SQL Authority See other posts from SQL Authority or by pinaldave
Published on Thu, 22 Nov 2012 01:30:18 +0000 Indexed on 2012/11/22 5:04 UTC
Read the original article Hit count: 540

Earlier I wrote a blog post about Remvoing Leading Zeros from Column In Table. It was a great co-incident that my friend Madhivanan (no need of introduction for him) also post a similar article over on BeyondRelational.com. I strongly suggest to read his blog as well as he has suggested some cool solutions to the same problem.

On original blog post asked two questions 1) if my sample for testing is correct and 2) If there is any better method to achieve the same. The response was amazing. I am proud on our SQL Community that we all keep on improving on each other’s contribution. There are some really good suggestions as a comment. Let us go over them right now.

Improving the ResultSet

I had missed including all zeros in my sample set which was an overlook. Here is the new sample which includes all zero values as well.

USE tempdb
GO
-- Create sample table
CREATE TABLE Table1 (Col1 VARCHAR(100))
INSERT INTO Table1 (Col1)
SELECT '0001'
UNION ALL
SELECT '000100'
UNION ALL
SELECT '100100'
UNION ALL
SELECT '000 0001'
UNION ALL
SELECT '00.001'
UNION ALL
SELECT '01.001'
UNION ALL
SELECT '0000'
GO

Now let us go over some of the fantastic solutions which we have received.

Response from Rainmaker

SELECT
CASE PATINDEX('%[^0 ]%', Col1 + ' ‘')
WHEN 0 THEN ''
ELSE SUBSTRING(Col1, PATINDEX('%[^0 ]%', Col1 + ' '), LEN(Col1))
END
FROM
Table1

Response from Harsh Solution 1

SELECT
SUBSTRING(Col1, PATINDEX('%[^0 ]%', Col1 + 'a'), LEN(Col1))
FROM Table1

Response from Harsh Solution 2

SELECT
RIGHT(Col1, LEN(Col1)+1 -PATINDEX('%[^0 ]%', Col1 + 'a' ))
FROM Table1

Response from lucazav

SELECT
T.Col1
, label = CAST(
CAST(REPLACE(T.Col1, ' ', '') AS FLOAT)
AS VARCHAR(10))
FROM Table1 AS T

Response from iamAkashSingh

SELECT REPLACE(LTRIM(REPLACE(col1,'0',' ')),' ','0') FROM table1

Here is the resultset of above scripts. It will remove any leading zero or space and will display the number accordingly.

If you believe there is a better solution, please leave a comment. I am just glad to see so many various responses and all of them teach us something new.

Reference: Pinal Dave (http://blog.sqlauthority.com)


Filed under: PostADay, SQL, SQL Authority, SQL Function, SQL Query, SQL Server, SQL Tips and Tricks, T SQL, Technology

© SQL Authority or respective owner

Related posts about PostADay

Related posts about sql