【问题标题】:Why isn't STUFF and FOR XML PATH not concenating?为什么 STUFF 和 FOR XML PATH 不集中?
【发布时间】:2014-01-10 18:14:52
【问题描述】:

我有这两张桌子

CREATE TABLE [dbo].[Things](
    [testid] [int] NOT NULL,
    [testdesc] [varchar](10) NULL
) ON [PRIMARY]

CREATE TABLE [dbo].[ThingsStaging](
    [otherid] [int] NOT NULL,
    [testid] [int] NOT NULL
) ON [PRIMARY]

INSERT INTO [dbo].[Things] ([testid], [testdesc]) VALUES (1, N'Stuff')
INSERT INTO [dbo].[Things] ([testid], [testdesc]) VALUES (2, N'Things')
INSERT INTO [dbo].[Things] ([testid], [testdesc]) VALUES (3, N'Orcs')
INSERT INTO [dbo].[Things] ([testid], [testdesc]) VALUES (4, N'Grubs')
INSERT INTO [dbo].[Things] ([testid], [testdesc]) VALUES (5, N'Shrooms')

INSERT INTO [dbo].[ThingsStaging] ([otherid], [testid]) VALUES (1, 1)
INSERT INTO [dbo].[ThingsStaging] ([otherid], [testid]) VALUES (1, 2)
INSERT INTO [dbo].[ThingsStaging] ([otherid], [testid]) VALUES (1, 3)
INSERT INTO [dbo].[ThingsStaging] ([otherid], [testid]) VALUES (2, 3)
INSERT INTO [dbo].[ThingsStaging] ([otherid], [testid]) VALUES (2, 4)

;with allThings(otherid, descs)
as 
(
    select ts.otherid ,
    stuff ((select ', ' + blah.testdesc  as [text()]
            from (
                select distinct t.testdesc 
                from Things as t
                where t.testid = ts.testid ) as blah 
                for xml path('')), 1, 1, '') as stuffs
    from ThingsStaging as ts 
)
select *
from allThings 

现在当运行这个查询时,我得到了

otherid stuffs
1    Stuff
1    Things
1    Orcs
2    Orcs
2    Grubs

但我应该得到:

otherid     stuffs
1     Stuff, Things, Orcs
2     Orcs, Grubs

我不明白我做错了什么。

【问题讨论】:

    标签: sql sql-server-2012 for-xml-path


    【解决方案1】:

    我明白我做错了什么。代码会更好地解释。

    select otherid, stuff((select ', ' + t.testdesc as [text()]
                            from Things as t
                            inner join ThingsStaging as its on t.testid = its.testid
                            where its.otherid = ts.otherid
                            for xml path('')), 1, 1, '') as descs
    from ThingsStaging as ts
    group by otherid
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-16
      • 2015-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-29
      • 2015-07-14
      相关资源
      最近更新 更多