-->

Using part of date in CAML query

2019-07-17 02:44发布

问题:

The title column in my list contains year only. I want to make a view, where I would display only last 3 years.

I'm trying to use CAML query in List definition:

<Query>
  <Where>
    <Geq>
      <FieldRef Name="Year" />
      <Value Type="Number"> ???? </Value>
    </Geq>
  </Where>
</Query>

I was trying to get something here using <Today> element with Offset attribute, but without luck - it's not a DateTime value, but only a number.

How to write filtering condition here?

回答1:

Since it's not a datetime value ,it will never work with <Today> and offset because these elements are internally convert to SQL DateTime value based on the moment the query is run.

You could create a view where you're looking for any entry above 2009 (as of right 2012) but that would require additional minor work each year to adapt.

I would suggest if possible to create a real date only field and work with it (and maybe only display a calculated field based on that value).



回答2:

I would recommend to do this in two steps:

  1. Create a calculated field of type DateTime (without time) using formulas described here http://msdn.microsoft.com/en-us/library/bb862071.aspx. It will be something like this =DATE(Year-3,0,0)
  2. Do a query using this new column. Something like
<Geq>
        <FieldRef Name="YearCalculated" />
        <Value Type="DateTime" IncludeTimeValue="FALSE"><Today /></Value>    
</Geq>

Approach with Offset="-1095" may also work, but i think substracting year value in calculated field will work better. Plus you can always make your calculated field invisible on view forms if required.