We help IT Professionals succeed at work.
Get Started

Inserting Line Breaks into SQL function return string

482 Views
Last Modified: 2012-05-12
Using SQL Server 2008, I have a function that creates a string of account numbers and addresses.  I want to put a line break between each account/address string, but cannot make it happen.  I've tried adding CHAR(13) and CHAR(10) without success.  The output I want should look like this:

12345 - 123 street name
54321 - 321 street name

But it's coming out like this:

12345 - 123 street name 54321 - 321 street name
FUNCTION [dbo].[ActiveAccountStrings] 
(
	@pClientID varchar(50)
)
RETURNS varchar(255)  
AS
BEGIN
declare @accounts int
declare @cnt int
declare @accountstring varchar(255)
declare @lastaccount varchar(50)
declare @lastaccountid int
declare @siteaddress varchar(255)

DECLARE @LINEBREAK AS varchar(2)
SET @LINEBREAK = CHAR(13) + CHAR(10)

select @accounts = count(*) 
 from ppaccounts pp (nolock) 
 inner join tiebacks t (nolock) on t.tiebackid = pp.tiebackid and t.clientid = @pClientID 
 where pp.status = 'A'

select @cnt = 1
select @lastaccount = ''
select @accountstring = ''
select @lastaccountid = -1

while (@cnt <= @accounts)
begin
  select @lastaccount = min(pp.account) 
  from ppaccounts pp (nolock) 
  inner join tiebacks t (nolock) on t.tiebackid = pp.tiebackid and t.clientid = @pClientID
  where pp.status = 'A' and pp.id > @lastaccountid
  
  select @lastaccountid = pp.id 
  from ppaccounts pp (nolock) 
  where pp.account = @lastaccount
  
  select @siteaddress = pp.ppsiteaddress 
  from ppaccounts pp (nolock) 
  where pp.account = @lastaccount
  
  if @accountstring <> '' 
  begin
    select @accountstring = @accountstring + @LINEBREAK + @lastaccount + ' - ' + @siteaddress
  end
  else
  begin
    select @accountstring = @lastaccount + ' - ' + @siteaddress
  end
  select @cnt = @cnt + 1
end

return @accountstring

END

Open in new window

Comment
Watch Question
CERTIFIED EXPERT
Top Expert 2010
Commented:
This problem has been solved!
Unlock 2 Answers and 10 Comments.
See Answers
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE