加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

sql – 如何在COALESCE()中获取不同的值

发布时间:2020-12-12 06:49:03 所属栏目:MsSql教程 来源:网络整理
导读:我有这种格式的表值 samjacksamjohnDeclare @name varchar(max)select @name = COALESCE(@name + ',','')+ user_email from PostedCommentMaster where article_id = @id 我怎样才能获得不同的价值 sam,jack,john 像这样. 解决方法 您可以将select语句包装到
我有这种格式的表值
sam
jack
sam
john

Declare @name varchar(max)
select @name = COALESCE(@name + ',','')+ user_email 
from   PostedCommentMaster where article_id = @id

我怎样才能获得不同的价值

sam,jack,john

像这样.

解决方法

您可以将select语句包装到子选择中并对结果应用合并.
Declare @name varchar(max) 

select @name = COALESCE(@name + ','') + user_email 
from   (select distinct user_email 
        from   PostedCommentMaster 
        where article_id = @id) pc

请注意,这使用SQL Server的未记录功能将结果连接成一个字符串.虽然我找不到它的链接,但我记得读到你不应该依赖这种行为.

更好的选择是使用FOR XML语法返回连接字符串. A search on SO返回可以用作示例的多个结果.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读