CAML queries of Lookup columns support query by ID

When you run a CAML query, you have to specifiy a value you’re searching for:

query.Query = "<Where><Eq><FieldRef Name='MyField' /><Value Type='Text'>WhatILookFor</Value></Eq></Where>";

Well, that’s fine, but what about lookup columns? They actually have 2 elements – the text, and an ID.

E.g. You might have a lookup to a ‘Country’ list, and “United Kingdom” might be ID 45.

If I wanted to find items on my list that referenced the “United Kingdom” value, my query would be:

query.Query = "<Where><Eq><FieldRef Name='MyField' /><Value Type='Lookup'>United Kingdom</Value></Eq></Where>";

However, this doesn’t make much sense. The ID is our primary key to the ‘country’ list. Why are we querying by value? I mean, if the United Kingdom had a revolution and suddenly became, say, the ‘United Republic’, all of my CAML queries would break.

(That might be the least of my worries, but you get my point).

So, we’d like to query by ID. Well, you can – I’ve mentioned it before, and the MSDN documents neglect to mention it themselves. There is a property on the FieldRef of LookupId. Set that to True, and you can query by ID.

query.Query = "<Where><Eq><FieldRef Name='MyField' LookupId='TRUE' /><Value Type='Lookup'>43</Value></Eq></Where>";

Edit: One of my colleagues pointed out that in SharePoint 2010, if you update the text of a referenced item, it is updated within the items that reference it. This is different to SharePoint 2007, where the referencing items retained the original text value. He’s right – but I’d still prefer to query by ID as it’s indexed, unique, and simple.

Advertisements
CAML queries of Lookup columns support query by ID

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.