Reputation: 139
I have the values in column 01 which i want to convert as values in Column 02, removing all the zero's from end. Is there a way to do this in SQL server ?
Column 01 Column 02
20100000 201
29050000 2905
Thanks in anticipation.
Upvotes: 0
Views: 62
Reputation: 175726
For positive integers only you could use:
CREATE TABLE #tab(col1 INT);
INSERT INTO #tab(col1) VALUES (20100000),(29050000);
SELECT col1, REVERSE(REVERSE(col1) + 0) + 0 AS trimmed
FROM #tab;
Output:
╔══════════╦═════════╗
║ Col1 ║ trimmed ║
╠══════════╬═════════╣
║ 20100000 ║ 201 ║
║ 29050000 ║ 2905 ║
╚══════════╩═════════╝
How it works:
0
-> implicit cast to INT
. You could use CAST/CONVERT
to be explicit !0
-> cast to INT
20100000
-> "0000102"
-> 102
-> "201"
-> 201
Added support for negative integer as well:
SELECT col1, SIGN(col1) * REVERSE(REVERSE(ABS(col1)) + 0) AS trimmed
FROM #tab;
Upvotes: 7
Reputation: 171
Or another way is to create a function to remove excess zeros, like this:
CREATE FUNCTION dbo.RemoveZeros(
@value BIGINT
) RETURNS BIGINT AS
BEGIN
DECLARE @str NVARCHAR(50)
SET @str = CAST(@value AS NVARCHAR(50))
WHILE ((LEN(@str)>0) AND (RIGHT(@str,1)=N'0'))
SET @str = LEFT(@str,LEN(@str)-1)
RETURN @str
END
Upvotes: 0