I have these two Microsoft SQL Server 2005 tables:
ObjectLicenses (ObjectLicenseID [PK]; ObjectID; LicenseType; LicenseNumber)
1|1|A|000001
2|1|A|000002
3|1|B|000003
4|2|C|000004
Objects (ObjectID [PK])
1
2
3
Table ObjectLicenses has a primary key on column ObjectLicenseID. Table Objects has a primary key on column ObjectID.
I want to return a list of all LicenseType's, by Object ID. However, this takes a long time, possibly due to lack of index(es)...currently, I use a "FOR XML PATH" query to do this:
SELECT O.ObjectID
,STUFF( (SELECT '; ' +
CONVERT(VARCHAR(12), ROW_NUMBER() OVER
(ORDER BY OL.ObjectLicenseID)) +
') ' + ISNULL(OL.LicenseType, '')
FROM ObjectLicenses OL
WHERE O.ObjectID = OL.ObjectID
FOR XML PATH(''), TYPE
).value('.', 'VARCHAR(MAX)')
, 1, 2, ''
) AS 'LicenseType'
FROM Objects O
How might I index or otherwise change this model/query to speed it up?
varcharwithout specifying a length (in this case,12is probably fine). – Aaron Bertrand Jun 20 '12 at 17:27varchar, sayvarchar(whatever the max need is)... hat way you don't get surprised because in one case you'll get avarchar(30)and in others you'll get avarchar(1). Note that my comment wasn't meant as a fix for your performance issue, just a fix for the bad habit of not bothering to specify the length of your varchar variables/conversions. – Aaron Bertrand Jun 28 '12 at 18:37TYPE).value...stuff is probably unnecessary. That's primarily used to prevent problems with XML entitization - it doesn't look like your sample data could contain &, >, < etc. – Aaron Bertrand Jun 28 '12 at 18:48