鉴于以下内容 - 如何在SQL Server中用0替换尾随空格?
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
答案 0 :(得分:3)
您可以利用LEN和DATALENGTH的差异。 LEN删除尾随空格,DATALENGTH不删除尾随空格。 REPLICATE将采用零长度参数
SELECT
RTRIM(TestField) + REPLICATE('0', DATALENGTH(TestField)-LEN(TestField))
FROM
TestTable
答案 1 :(得分:1)
怎么样:
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