0

Given the following - how can I replace trailing spaces with 0's in SQL Server?

CREATE TABLE TestTable
(
    TestField CHAR(8)
)   

INSERT INTO TestTable
SELECT ' 1 1 1  '   
INSERT INTO TestTable
SELECT ' 1 1 1 1'   

SELECT  
TestField,   
LEN(TestField) AS LenTestField,
REPLACE(TestField, ' ', '0') AS TestFieldReplaced,
LEN(REPLACE(TestField, ' ', '0')) AS LenTestFieldReplaced,
REPLACE(TestField, ' ', '0') + REPLICATE('0', DATALENGTH(TestField)-LEN(TestField)), 
REPLACE(CONVERT(VARCHAR,TestField), ' ', '0')
FROM    TestTable
2
  • I updated this to include an example from the accepted answer, using replicate as indicated below. Commented Jun 21, 2011 at 16:34
  • Apparently converting to varchar works as well. Commented Jun 23, 2011 at 22:21

2 Answers 2

3

You can leverage the difference in LEN and DATALENGTH. LEN removes trailing spaces,DATALENGTH doesn't. And REPLICATE will take a zero length parameter

SELECT
   RTRIM(TestField) + REPLICATE('0', DATALENGTH(TestField)-LEN(TestField))
FROM
   TestTable
Sign up to request clarification or add additional context in comments.

Comments

1

how about this:

DECLARE @test TABLE
(num nvarchar(30) )

INSERT INTO @test (num) VALUES ('1 1 1   ')

SELECT LEFT(num, LEN(num)) + REPLICATE('0', LEN(REPLACE(num, ' ', '*')) - LEN(num)) FROM @test

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.