开发者

Rows to field level in query?

Using SQL 2005, I am trying to run a query on a Orders table in my database. Each order can have multiple 'Comments'.

I want to get a single order record with all the Comments put together in one field.

Here is the psuedocode for what I'm trying to do:

SELECT 
Orders.Name, 
Orders.Date,
(SELECT Comment += Comment FROM OrderComments WHERE OrderComments.OrderId = Orders.OrderId)
FROM Orders

I want the Order Comments to end up as a field in my query, and be able to seperate the resulting rows by something like the date and a comma. Is there a way to merge the resulting rows from the subquery into one field?

So if there's:

**Orders:**
Order Id(int): 1
Order Name(varchar): First Order

**OrderComments:**
OrderId(int): 1
Comment(text): First order, yay

OrderId(int): 1
Comment(text): Just a random comment

I want to end up with a row like th开发者_C百科is(in this case a semi-colon delimiter): "First Order", "10/25/2010", "First order, yay; Just a random comment".

Thank you for any assistance!


Use for xml:

SELECT 
Orders.Name, 
Orders.Date,
(SELECT Comment +', ' FROM OrderComments WHERE OrderComments.OrderId = Orders.OrderId FOR XML PATH(''))
FROM Orders
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜