Remove trailing zeroes from varchar in sql

Gowsalya 21 Reputation points
2022-07-27T05:48:23.343+00:00

Hi,
I need to remove trailing zeroes from varchar value, but like decimal round off in SQL server.

Examples:
M12.00 -->M12
M12.70 -->M12.7
M120 -->M120
ABC -->ABC

Is there any best way to do so?

Thanks in advance.

Azure SQL Database
SQL Server Analysis Services
SQL Server Analysis Services
A Microsoft online analytical data engine used in decision support and business analytics, providing the analytical data for business reports and client applications such as Power BI, Excel, Reporting Services reports, and other data visualization tools.
1,344 questions
Developer technologies | Transact-SQL
SQL Server | Other
{count} votes

Accepted answer
  1. LiHong-MSFT 10,056 Reputation points
    2022-07-27T07:45:05.603+00:00

    Hi @Gowsalya
    Check this query:

    CREATE TABLE #TEST(Column1 VARCHAR(20))  
    INSERT INTO #TEST VALUES('M12.07'),('M12.010'),('M12.00'),('M12.70'),('M120'),('ABC')  
      
    SELECT CASE WHEN CHARINDEX('.',Column1)>0 AND RIGHT(Column1,1)='0'  
                THEN REVERSE(STUFF(REVERSE(Column1),1,PATINDEX('%[^0.]%',REVERSE(Column1))-1,''))  
    			ELSE Column1 END  
    FROM #TEST  
    

    Best regards,
    LiHong


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Yitzhak Khabinsky 26,586 Reputation points
    2022-07-27T13:31:26.297+00:00

    Hi @Gowsalya ,

    A cleaner and more concise solution based on the TRIM() function.
    It will work starting from SQL Server 2017 onwards.

    SQL

    -- DDL and sample data population, start  
    DECLARE @tbl TABLE (col VARCHAR(20));  
    INSERT INTO @tbl VALUES  
    ('M12.07'),('M12.010'),('M12.00'),('M12.70'),('M120'),('ABC');  
    -- DDL and sample data population, end  
      
    SELECT col AS [Before]  
    	, IIF(CHARINDEX('.',col) > 0 AND RIGHT(col,1) = '0',  
    		TRIM('.' FROM TRIM('0' FROM col)),  
    		col) AS [After]  
    FROM @tbl;  
    
    2 people found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.