<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"><channel><title>合并列 on 冯威的博客</title><link>https://fwhyy.com/tags/%E5%90%88%E5%B9%B6%E5%88%97/</link><description>Recent content in 合并列 on 冯威的博客</description><generator>Hugo</generator><language>zh-CN</language><lastBuildDate>Thu, 15 Oct 2009 00:00:00 +0800</lastBuildDate><atom:link href="https://fwhyy.com/tags/%E5%90%88%E5%B9%B6%E5%88%97/atom.xml" rel="self" type="application/rss+xml"/><item><title>在数据库中将字表中的多行合并到一列中</title><link>https://fwhyy.com/2009/10/words-in-the-table-in-the-database-multi-line-merged-into-a-column/</link><pubDate>Thu, 15 Oct 2009 00:00:00 +0800</pubDate><guid>https://fwhyy.com/2009/10/words-in-the-table-in-the-database-multi-line-merged-into-a-column/</guid><description>&lt;p&gt;几年前就做过这样的查询，在最近的项目中又遇到这样的需求，在此记录一下。&lt;/p&gt;
&lt;p&gt;假设有一个文章表Post和一个评论表Comments，可以对文章进行多次评论，现在希望在对Post表查询时能将Post的所有评论内容组合到一个字段中显示。&lt;/p&gt;
&lt;p&gt;首先创建表Post和Comments&lt;/p&gt;
&lt;pre tabindex="0"&gt;&lt;code&gt;create table Post
(
 [PostID] int identity(1,1) primary key not null,
 [Title] nvarchar(50),
 [Content] text,
 [CreateDate] datetime default getdate()
)

create table Comments
(
 [CommentID] int identity(1,1) primary key not null,
 [PostID] int,
 [Content] text,
 [CreateDate] datetime default getdate()
)
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;给这两个表添加一些测试数据&lt;/p&gt;
&lt;pre tabindex="0"&gt;&lt;code&gt;insert into Post select &amp;#39;钓鱼岛是中国的吗？&amp;#39;,&amp;#39;钓鱼岛是中国的&amp;#39;,getdate()
insert into Comments select 1,&amp;#39;绝对是&amp;#39;,getdate()
insert into Comments select 1,&amp;#39;必须是的&amp;#39;,getdate()
insert into Comments select 1,&amp;#39;谁说不是呢&amp;#39;,getdate()
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;评论内容的组合使用一个函数来实现，在函数中使用游标去遍历给定PostID的所有评论然后进行拼接，函数代码如下：&lt;/p&gt;
&lt;pre tabindex="0"&gt;&lt;code&gt;create FUNCTION fn_GetAllComments(@PostID int)
RETURNS NVARCHAR(4000)
AS
BEGIN
 DECLARE @result VARCHAR(4000)
 SET @result=&amp;#39;&amp;#39;
 DECLARE getAllComments CURSOR
 FOR
 select CommentID from Comments where PostID=@PostID
 OPEN getAllComments
 DECLARE @ID SYSNAME
 FETCH FROM getAllComments INTO @ID
 WHILE @@fetch_status=0
 BEGIN
 SET @result=@result+(select convert(nvarchar(20),CreateDate,120)
 from Comments where CommentID=@ID)+&amp;#39;:&amp;#39;+
 (select cast([Content] as nvarchar(4000))
 from Comments where CommentID=@ID)+&amp;#39;；&amp;#39;
 FETCH FROM getAllComments INTO @ID
 END
 CLOSE getAllComments
 SET @result= substring(@result,0,len(@result))
 DEALLOCATE getAllComments
 RETURN @result
END
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;现在写SQL语句来测试一下结果&lt;/p&gt;</description></item></channel></rss>