Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

build string from select statement

Posted on 2008-10-18
5
Medium Priority
?
861 Views
Last Modified: 2012-06-27
I am trying to build a select statement that I will pass to a tored proc as xml.  basically, I want to wrap the ids that are returned in xml tags, like this:
<id>123</id><id>234</id>
...the query statement I am trying to run looks like:
select distinct @myxml = '<id>' + convert(varchar(25), id) + '</id>'
from tbl_answers
where coalesce(IsCompleted, 0) = 0

This only returns the first value it hits (i.e. - <id>123</id>).  I also tried inserting the results into a table variable and building the string by selecting one row at a time, that didnt work either, it returns a null.

Any thoughts?
0
Comment
Question by:PsychoDazey
  • 3
  • 2
5 Comments
 
LVL 14

Expert Comment

by:Binuth
ID: 22751127
try this
declare @myxml as varchar(max)
set @myxml = ''
select @myxml = @myxml + '<id>' + convert(varchar(25), id) + '</id>'
from tbl_answers
where coalesce(IsCompleted, 0) = 0

Open in new window

0
 
LVL 6

Author Comment

by:PsychoDazey
ID: 22752642
That works until I put the distinct clause in.  For some reason as soon as I do that it only returns the first record....any ideas?
0
 
LVL 14

Accepted Solution

by:
Binuth earned 2000 total points
ID: 22755043

declare @myxml as varchar(max)
set @myxml = ''
select 
	@myxml = @myxml + '<id>' + convert(varchar(25), id) + '</id>'
from 
	(
		select Distinct id 
		from tbl_answers 
		where coalesce(IsCompleted, 0) = 0
	) Dist

Open in new window

0
 
LVL 6

Author Comment

by:PsychoDazey
ID: 22757962
Perfect, thanks!
0
 
LVL 6

Author Closing Comment

by:PsychoDazey
ID: 31507523
sorry, forgot to accept!
0

Featured Post

Configuration Guide and Best Practices

Read the guide to learn how to orchestrate Data ONTAP, create application-consistent backups and enable fast recovery from NetApp storage snapshots. Version 9.5 also contains performance and scalability enhancements to meet the needs of the largest enterprise environments.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For both online and offline retail, the cross-channel business is the most recent pattern in the B2C trade space.
When trying to connect from SSMS v17.x to a SQL Server Integration Services 2016 instance or previous version, you get the error “Connecting to the Integration Services service on the computer failed with the following error: 'The specified service …
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.
Via a live example, show how to setup several different housekeeping processes for a SQL Server.

886 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question