Read our blogs, tips and tutorials
Try our exercises or test your skills
Watch our tutorial videos or shorts
Take a self-paced course
Read our recent newsletters
License our courseware
Book expert consultancy
Buy our publications
Get help in using our site
538 attributed reviews in the last 3 years
Refreshingly small course sizes
Outstandingly good courseware
Whizzy online classrooms
Wise Owl trainers only (no freelancers)
Almost no cancellations
We have genuine integrity
We invoice after training
Review 30+ years of Wise Owl
View our top 100 clients
Search our website
We also send out useful tips in a monthly email newsletter ...
How to use the FOR XML keywords in SQL to concatenate ids Part two of a three-part series of blogs |
---|
If you want to group items in a SQL query, showing a comma-delimited list of ids for each, generating an XML file is not the obvious place to start - but it should be.
|
To explain what FOR XML PATH does, let's start with a basic query.
The following query creates basic XML text for Tulisa Bush (person number 1):
SELECT
p.PersonName,
p.CourseId
FROM
tblPerson AS p
WHERE
p.PersonId = 1
FOR XML PATH
This natty little query produces this:
The query creates a single output, which is an XML representation of the query results.
I've copied the output to a new XML file (you don't need to do this - it's just to show what XML is) to get:
XML is a way of showing relational data in a text format.
There are four keywords you can use after FOR XML (PATH, AUTO, EXPLICIT and RAW), but we just need the first one to get our concatenated ids to work.
I'm now going to tweak the query to this:
-- comma-separated ids
SELECT
',' + CAST(p.CourseId AS varchar(10))
FROM
tblPerson AS p
FOR XML PATH('')
Here's a list of what's changed:
Running this query produces this:
We just get the ids, separated by commas.
The XML omits any node names - just listing out the ids - because the column has no alias, and hence no name that SQL can pick up.
Now we've got a way to join the ids together, we need to group them for each person - the subject of the last part of this blog.
Parts of this blog |
---|
|
Some other pages relevant to the above blogs include:
Kingsmoor House
Railway Street
GLOSSOP
SK13 2AA
Landmark Offices
99 Bishopsgate
LONDON
EC2M 3XD
Holiday Inn
25 Aytoun Street
MANCHESTER
M1 3AE
© Wise Owl Business Solutions Ltd 2024. All Rights Reserved.