I have declalared a temp variable in sql. it contains a string A001, A011, A002, A14, A158.
i want to remove zeroes to get following output
A1, A2, A11, A14, A158
I have declalared a temp variable in sql. it contains a string A001, A011, A002, A14, A158.
i want to remove zeroes to get following output
A1, A2, A11, A14, A158
You can achieve what you're after with some string manipulation.
So if you take the first character from A010
:
DECLARE @SomeValue nvarchar(10) = 'A010'
SELECT LEFT(@SomeValue, 1) -- gives you 'A'
Then get the numeric part, by removing the first character and convert it to an integer:
SELECT CONVERT(INT, SUBSTRING(@SomeValue, 2, LEN(@SomeValue) - 1)) -- returns 10
This will remove the leading zeroes for you. You then just need to convert it back to a string and append it on to the first character.
Full working solution:
DECLARE @T1 TABLE ( SomeValue NVARCHAR(10) )
INSERT INTO @T1
( SomeValue )
VALUES ( 'A001' ),
( 'A011' ),
( 'A002' ),
( 'A14' ),
( 'A158' ),
( 'A010' )
SELECT SomeValue AS Original ,
LEFT(SomeValue, 1)
+ CONVERT(NVARCHAR(10),
CONVERT(INT, SUBSTRING(SomeValue, 2, LEN(SomeValue)-1))) RemoveLeadingZeroes
FROM @T1
Use this: (I used XML to replace extract each word and then replaced the 0's by casting 0010 to 10 and combined the values A + 10 to get A10 and again combined the each word to form A1, A2, A14..)
DECLARE @string VARCHAR(MAX),
@Split CHAR(1),
@X xml
SELECT @string = 'A001, A011, A002, A14, A158',
@Split = ', '
SELECT @X = CONVERT(xml,'<root><s>' + REPLACE(@string,@Split,'</s><s>') + '</s></root>')
SELECT
STUFF(((SELECT ', ' + CAST(Result AS VARCHAR(100)) FROM
(SELECT SUBSTRING(LTRIM(Result), 1, 1) +
CAST(CAST(SUBSTRING(LTRIM(Result), 2, LEN(LTRIM(Result))) AS INT) AS VARCHAR) AS Result
FROM
(SELECT T.c.value('.','varchar(max)') AS Result
FROM @X.nodes('/root/s') T(c)) AS NewResult)
AS NewResult1
FOR xml path(''), type).value('.','varchar(max)')), 1,2,'')
AS FinalResult
SqlFiddle: Demo