SQL REPLICATE - weird results -
perhaps i've been @ few many hours, there odd results of statement.
the result of statement
(1) datalength(rtrim([last name])) last_name_length
is 10.
the result of next statement, want use padding last_name column spaces,
(2) datalength(replicate(' ', (30 - datalength(rtrim([last name])))))
is 20.
you think result of statement,
(3) datalength(rtrim([last name]) + replicate(' ', 30 - datalength(rtrim([last name]))))
would 30.
it isn't. it's 50. result of statement (3) consistently greater of statement (2) 30. it's if i'm using + operator in replicate statement instead of -.
i've googled again , again , don't see what's wrong syntax. appreciated.
it looks want pad 30 chars, use str
select str([last name], 30)
original answer below
can replicate issue
declare @last_name nvarchar(30) set @last_name = '12345' select datalength(rtrim(@last_name)) last_name_length, datalength(replicate(' ', (30 - datalength(rtrim(@last_name))))), datalength(rtrim(@last_name) + replicate(' ', 30 - datalength(rtrim(@last_name))))
output
last_name_length ---------------- ----------- ----------- 10 20 50
to fix it, using len doesn't work, results in (because trailing spaces not counted)
last_name_length ---------------- ----------- ----------- 5 0 5
instead, divide datalength results 2
declare @last_name nvarchar(30) set @last_name = '12345' select datalength(rtrim(@last_name))/2 last_name_length, datalength(replicate(' ', 30 - datalength(rtrim(@last_name))))/2, datalength(rtrim(@last_name) + replicate(' ', 30 - datalength(rtrim(@last_name))/2))/2
Comments
Post a Comment