Tuesday, May 8, 2012

Filtering list items by user id using CAML in SPSiteDataQuery

I had some struggle finding out how to filter the list items by a particular user (SharePoint user). I am sure that this can be done but the filter does not seem to work for me if it is using the field value as "Integer". It was working very fine if the filter is applied for current logged in user as below:

<Query>
  <Where>
    <Eq>
      <FieldRef Name="Author" />
      <Value Type="Integer">
        <UserID Type="Integer" />
      </Value>
    </Eq>
  </Where>
</Query>
 
Of course, this only works if the filtering is applied for the currently logged in user. so, what does need to happen when the query needs to filter based on another user?

I tried the above CAML by replacing the <UserID Type="Integer" /> with the particular user's id value (SPUser.ID). This does not seem to work. Always it returns no items.

<Query>
  <Where>
    <Eq>
      <FieldRef Name="Author" />
      <Value Type="Integer">
        75
      </Value>
    </Eq>
  </Where>
</Query>


It turns out to be an attribute "LookupId" needs to be added to the <FieldRef> element as below.
 
<Query>
  <Where>
    <Eq>
      <FieldRef Name="Author" LookupId="True"/>
      <Value Type="Integer">
        75
      </Value>
    </Eq>
  </Where>
</Query>
 
Happy Coding.
Senthil S

2 comments:

  1. excelent, thank you!!

    ReplyDelete
  2. Mate, thank you for writing this blog post. This is exactly what I've been struggling with today. Finally I understand.

    ReplyDelete