Recently, I came across a query in a blog, ‘How to remove leading zeros after a decimal point’. I then started developing the shortest possible solution and thought of sharing with my blog readers. Let me create a sample to demonstrate the solution.
DECLARE @tbl_sample AS TABLE ( [ID] INT, [Col_Varchar] VARCHAR(50) ) INSERT INTO @tbl_sample VALUES (1,'2013.0000000001') INSERT INTO @tbl_sample VALUES (2,'2014.0000000002') INSERT INTO @tbl_sample VALUES (3,'2015.0000000003') INSERT INTO @tbl_sample VALUES (4,'2016.0000000044') INSERT INTO @tbl_sample VALUES (5,'2017.0000000555') SELECT * FROM @tbl_sample --OUTPUT
SOLUTION 1 :
Given below is the solution using PARSENAME & CONCAT function.
--This script is compatible with SQL Server 2012 and above. SELECT [ID] ,CONCAT(PARSENAME([Col_Varchar],2) ,'.',CONVERT(INT,PARSENAME([Col_Varchar],1))) AS [Col_Varchar] FROM @tbl_sample --OUTPUT
SOLUTION 2 :
Given below is the solution using PARSENAME & CONVERT function.
--This script is compatible with SQL Server 2005 and above. SELECT [ID] ,CONVERT(VARCHAR(5),PARSENAME([Col_Varchar],2)) + '.' + CONVERT(VARCHAR(5),CONVERT(INT,PARSENAME([Col_Varchar],1))) AS [Col_Varchar] FROM @tbl_sample --OUTPUT
it’s good function and u used it in good way but here you missed meaning of 1,2,3,4 argument of parsename function 🙂
Thanks Aryan,
Basically, if I do not use it like this it will be a long solution and not optimized as well.
Imran