7
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

This query gives 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 do I rewrite this query to work so that I get all the values into one variable? The end result need to be a "View" that looks like this:

.ObjectID int

.Content (string with all text that exists in the Forumthread.threadText and forumReply.ReplyText)

.Domain string

.SiteID int

2
  • That is exactly what I don`t want. I want all recordsets and join them together into one value Commented Mar 10, 2011 at 16:25
  • 1
    You can concatenate values from multiple rows into a string in SQL Server using XML PATH Commented Mar 10, 2011 at 16:29

4 Answers 4

24

Building upon Martin's comment:

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 the Fish!')

SELECT (SELECT replytext + ' '  FROM @t FOR XML PATH('')) AS CONTENT
Sign up to request clarification or add additional context in comments.

1 Comment

Number 3 should be "all the fish" ;)
2

You can assign to local variable this way.

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

1 Comment

@t is DECLARE @t TABLE (id int, ReplyText varchar(100))
1

I used 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

Result:

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

Comments

0

What you need is a string concat aggregate function, which sql server unfortunuatley does not include.

You can create your own though using .Net CLr function see here and here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.