Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 SQL 2000 and FOR XML

Author  Topic 

waveform
Yak Posting Veteran

93 Posts

Posted - 2014-01-30 : 15:30:13
In SQL 2000, I have 2 tables, in a 1-to-many r/ship, like this:



A standard query to get Order and Item rows would be:

SELECT o.ordernumber, i.itemnumber, i.description
FROM SalesOrder o INNER JOIN Item i ON o.ordernumber = i.ordernumber
Which of course results in 1 row returned per Item.

However, I'd like to "flatten" the results, so there is 1 row returned *per SalesOrder*, with each Item row turned into a single XML string field.

For example, instead of this result:

ordernumber itemnumber description
----------- ---------- -----------
1 1 foo
1 2 bar
2 3 morefoo
etc

I'd like to get this result:

ordernumber ItemXML
----------- -------------------
1 <row itemnumber="1" description="foo"/><row itemnumber="2" description="bar"/>
2 <row itemnumber="3" description="morefoo"/>
etc


Can this be done in SQL 2000 using the FOR XML function?

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2014-01-31 : 07:53:24
Try

SELECT DISTINCT ordernumber,
(SELECT itemnumber, description FROM table WHERE ordernumber = t.ordernumber FOR XML RAW)
FROM table t


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page

waveform
Yak Posting Veteran

93 Posts

Posted - 2014-01-31 : 17:24:58
Thanks visakh, however when I try that format in Query Analyser, I get the error:

Server: Msg 170, Level 15, State 1, Line 2
Line 2: Incorrect syntax near 'XML'.

If I try the subquery on its own (with a valid WHERE clause, eg. "ordernumber = 1") it works ok.

I can't see a problem with your suggestion - do you know what the error means?

Edit: Here's a screenshot of a simple query on an existing table. First without the "FOR XML", then with it:



(with or without brackets around the WHERE clause, same result)

Go to Top of Page
   

- Advertisement -