在SQL Query中将多个行选择为一个变量

时间:2011-03-10 16:17:39

标签: sql sql-server-2008

SELECT ft.ThreadTitle AS Title, 
fr.ReplyText + ' ' + ua2.Username + ' ' + ft.ThreadText + ' '  +

-- THIS NEXT LINE IS WHAT I WANT TO ACHIEVE:

(Select ReplyText from ForumReply Where ThreadID=ft.ThreadID) 

-- THE ABOVE LINE HAVE MULTIPLE ROWS/VALUES THAT I WANT TO JOIN INTO ONE VARIABLE. HOW?
AS [Content], 

ss.Domain, 
ss.SiteID, 
ft.ThreadID AS ObjectId
FROM         dbo.ForumReply AS fr INNER JOIN
                      dbo.ForumThreads AS ft ON fr.ThreadID = ft.ThreadID INNER JOIN
                      dbo.User_Account AS ua1 ON ft.CreateByUserID = ua1.UserID INNER JOIN
                      dbo.User_Account AS ua2 ON fr.ReplyUserID = ua2.UserID INNER JOIN
                      dbo.SysT_Site AS ss ON ua1.SiteID = ss.SiteID

此查询给出错误: 子查询返回的值超过1。当子查询遵循=,!=,<,< =,>,> =或子查询用作表达式时,不允许这样做。

如何重写此查询以便将所有值都放入一个变量中?最终结果需要是一个" View"看起来像这样:

.ObjectID int

.Content(包含Forumthread.threadText和forumReply.ReplyText中存在的所有文本的字符串)

.Domain string

.SiteID int

4 个答案:

答案 0 :(得分:18)

以马丁的评论为基础:

DECLARE @t TABLE  (id int, ReplyText varchar(100))
INSERT INTO @t (id, ReplyText) VALUES (1, 'So Long,')
INSERT INTO @t (id, ReplyText) VALUES  (2, 'And Thanks for')
INSERT INTO @t (id, ReplyText) VALUES  (3, 'All of the Fish!')

SELECT (SELECT replytext + ' '  FROM @t FOR XML PATH('')) AS CONTENT

答案 1 :(得分:1)

你需要的是一个字符串concat聚合函数,sql server unfortunuatley不包含它。

您可以使用.Net CLr功能创建自己的功能,请参阅herehere

答案 2 :(得分:1)

您可以这种方式分配给本地变量。

SELECT @TempVariable = (SELECT replytext + ' ' FROM @t FOR XML PATH(''))

答案 3 :(得分:1)

我用过STUFF:

SELECT
MyTable.Number AS Number,
(SELECT stuff(
    (
    select ', ' + x from (SELECT MyOtherTable.Name AS x FROM MyOtherTable WHERE MyOtherTable.ID = MyTable.ID) tb 
    FOR XML PATH('')
    )
, 1, 2, ''))AS AllNames

FROM
MyTable

结果:

Number:   AllNames:
  1       Andrew, Carl
  2       Bobby, Dave