问题
I am using SQL Server 2012 and I have the following two tables
Blog
Id Title
1 My Blog Title
BlogContent
Id Blogid Content
1 1 <p>My First Paragraph</p>
2 1 <p>My Second Paragraph</p>
Each Blog Entry may have multiple Content entries. This is a varchar field that contains HTML content. I need to select a blog and all of its content combined together.
here is what I tried:
SELECT B.Id, B.Title,
STUFF(( SELECT '' + BC.Content
FROM BlogContent BC
WHERE B.Id = BC.Blogid
ORDER BY BC.Id ASC OFFSET 0 ROWS
FOR XML PATH('')),1,0,'') AS Content
FROM Blog B
WHERE B.Id = 1
ORDER BY B.PublishDate DESC
And it almost worked, this is my result:
Id Title Content
1 My Blog Title <p>This is the first Message</p><p>This is the second Message</p>
My problem with the code above is that everything became HTML Encoded, I assume its because of FOR XML. How can I achieve combining without adding this part? If I don't add it then I get an error.
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
How can I get the following result:
Id Title Content
1 My Blog Title <p>This is the first Message</p><p>This is the second Message</p>
回答1:
Assuming ID in BlogContent is the proper sequence.
Example
Declare @Blog table (ID int, Title varchar(max))
Insert Into @Blog values
(1,'My Blog Title')
Declare @BlogContent table (ID int,Blogid int, Content varchar(max))
Insert Into @BlogContent values
(1,1,'<p>My First Paragraph</p>'),
(2,1,'<p>My Second Paragraph</p>')
Select A.*
,Content = Stuff((Select '' +Content
From @BlogContent
Where Blogid=A.ID
Order by ID
For XML Path(''),TYPE).value('(./text())[1]','varchar(max)')
,1,0,'')
From @Blog A
Returns
ID Title Content
1 My Blog Title <p>My First Paragraph</p><p>My Second Paragraph</p>
来源:https://stackoverflow.com/questions/49327612/combine-multiple-html-rows-into-one