Link to home
Start Free TrialLog in
Avatar of MoreThanDoubled
MoreThanDoubled

asked on

How to remove char(13) + char(10) from the END of a string

I have a sql variable that holds appended record set values that include char(13) + char(10) .

At the very end of the string (not within the string) i will need to remove the char(13) + char(10) .

For example i could have a string variable with the following:

Address: char(13) + char(10) 689 Will Street char(13) + char(10) Columbus char(13) + char(10) GA

But the actual result i would be looking to be removed is bolded below:
Address: char(13) + char(10) 689 Will Street char(13) + char(10) Columbus char(13) + char(10) GA


Thanks,
Avatar of Dale Fye
Dale Fye
Flag of United States of America image

Didn't we just build this string the other day?

That isn't actually "at the very end of the string" is it, since the state characters follow those values.

You might start by using the InstrRev( ) function to look for the last position where those to characters are found together in the sting.

To check your table, you could try:

SELECT [yourField], Left(yourField, instrrev([yourField], chr$(13) & chr$(10))-1)
FROM yourTable
WHERE InstrRev(yourString, chr$(13) & chr$(10)) <> 0
Do you just want to SELECT the rows or do you want to UPDATE the values?

Here's the SELECT to do that; if you press Ctrl-T before running, you can see the affects of the CR+LF in the output results:

SELECT
    address_string AS address_string,
    STUFF(address_string, LEN(address_string) - CHARINDEX(char(10) + char(13), REVERSE(address_string)), 2, ' ') AS address_string_new

FROM (
    select char(13) + char(10) + '689 Will Street' + char(13) + char(10) + 'Columbus' + char(13) + char(10) + 'GA' as address_string
) AS test_data
with t as
(select reverse(address) as address,charindex(char(10) + char(13), reverse(address) - 1) as pos
 from yourtable)
select reverse(left(address,pos) + ' ' + right(address,len(address) - pos - 2)) as newaddress
from t;
Sorry, i missed that this was posted to the SQL Server topic area
ASKER CERTIFIED SOLUTION
Avatar of Hamed Nasr
Hamed Nasr
Flag of Oman image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
How well does that work if the address line was? -
Address: + char(13) + char(10) +  1 Main St. + char(13) + char(10) +  Ames + char(13) + char(10) +  IA
awking00,

For the mentioned  pattern, compare with:
set @p='+ char(13) + char(10) +  1 Main St. + char(13) + char(10) +  Ames + char(13) + char(10) +  IA '
set @p= rtrim(replace(@p,'  ',' '));
select left(@p,len(@p)-26)+right(@p,3)

Open in new window

hnasr,
I agree that what you have posted will return what is wanted in these two cases, but I think what is really desired is code that will work for any combination of addresses.
Apparently that's not what is really desired, since I posted such code two days before hnasr's code.