0

I've an issue with caml query. I'm trying to get the last item created this year but still have only one item while i'm having 4 in my list and remover

I execute this in an event receiver itemAdding and in caml query builder

Here is my query

<Query>
<Where>
    <Geq>
        <FieldRef Name='Created'/>
        <Value Type='DateTime'>2014-01-01:00:00:00</Value>
    </Geq>
    <Leq>
        <FieldRef Name='Created'/>
        <Value Type='DateTime'>2014-12-31:23:59:59</Value>
    </Leq>
</Where>
<OrderBy>
    <FieldRef Name='ID' Ascending='False' />
</OrderBy>

Thanks a lot

2

First of all, Is it server or client object model? In case of SSOM you don't need Query node inside your CAML. And you forgot to wrap your Geq and Leq nodes with the And. So instead of this:

<Query>
<Where>
    <Geq>
        <FieldRef Name='Created'/>
        <Value Type='DateTime'>2014-01-01:00:00:00</Value>
    </Geq>
    <Leq>
        <FieldRef Name='Created'/>
        <Value Type='DateTime'>2014-12-31:23:59:59</Value>
    </Leq>
</Where>
<OrderBy>
    <FieldRef Name='ID' Ascending='False' />
</OrderBy>

you need to do something line this:

<Where>
<And>
    <Geq>
        <FieldRef Name='Created'/>
        <Value Type='DateTime'>2014-01-01T00:00:00Z</Value>
    </Geq>
    <Leq>
        <FieldRef Name='Created'/>
        <Value Type='DateTime'>2014-12-31T23:59:59Z</Value>
    </Leq>
</And>
</Where>    
<OrderBy>
    <FieldRef Name='ID' Ascending='False' />
</OrderBy>

There is an error in your date format. Also, note that time in CAML has to be in ISO 8601 format. Here is an example of the way you can get the right format:

SPUtility.CreateISO8601DateTimeFromSystemDateTime(new DateTime(2014,04,30);

OR:

dateTime.ToString("yyyy-MM-ddTHH:mm:ssZ")

Anyway, in order to build CAML with no mistakes, you might want to use U2U CAML Builder or any other CAML Builder that helps you to create CAML visually. In case of SharePoint 2013, you can use CAML Designer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.