Friday, March 15, 2013

CAML Query Issues SharePoint


CAML Builder code
<Query><Where><And><Eq><FieldRef Name="Created" /><Value Type="DateTime">[Today+1Day(s)]</Value></Eq></And></Where></Query>

Remove <Query> node as shown below in the coding

<Where><And><Eq><FieldRef Name="Created" /><Value Type="DateTime">[Today+1Day(s)]</Value></Eq></And></Where>


CAML Builder code
<Value Type="DateTime">[Today+1Day(s)]</Value>

Update as shown below in the coding

Get offsetdays value at runtime
<Value Type='DateTime'><Today OffsetDays='" + offsetdays + "'/></Value>

You can hard code like this

<Today OffsetDays='5'/></Value>


Below format is not supporting some times in the coding

   <Where>
      <And>
         <Eq>
            <FieldRef Name='Created' />
            <Value Type='DateTime'><Today OffsetDays='5'/></Value>
         </Eq>
      </And>
   </Where>

Always use below format in the coding

<Where><And><Eq><FieldRef Name="Created" /><Value Type="DateTime><Today OffsetDays='5'/></Value></Eq></And></Where>


   
Sample caml query function

        private static string CreateCAMLQuery(string symbol,string offsetdays,string redcnt)
        {
            string strQuery = string.Empty;

            switch (symbol.ToLower())
            {
                case "green":
                    strQuery = "<Where><And><IsNull><FieldRef Name='Actual_Date' /></IsNull><Geq><FieldRef Name='Target_Date' /><Value Type='DateTime'><Today OffsetDays='" + offsetdays + "'/></Value></Geq></And></Where>";
                    return strQuery;
                case "yellow":
                    strQuery = "<Where><And><IsNull><FieldRef Name='Actual_Date' /></IsNull><And><Gt><FieldRef Name='Target_Date' /><Value Type='DateTime'><Today OffsetDays='" + redcnt + "'/></Value></Gt><Leq><FieldRef Name='Target_Date' /><Value Type='DateTime'><Today OffsetDays='" + offsetdays + "'/></Value></Leq></And></And></Where>";
                    return strQuery;
                case "red":
                    strQuery = "<Where><And><IsNull><FieldRef Name='Actual_Date' /></IsNull><Leq><FieldRef Name='Target_Date' /><Value Type='DateTime'><Today OffsetDays='" + offsetdays + "'/></Value></Leq></And></Where>";
                    return strQuery;
                default:
                    return null;
            }
        }


Call caml query function
    if (item["Days_x0020_for_x0020_Green"] != null)
                                           {
                                               queryGreen.Query = CreateCAMLQuery("green", item["Days_x0020_for_x0020_Green"].ToString(), "0");
                                               SPListItemCollection itemsGreen = list.GetItems(queryGreen);
                                               drow1[1] = "/_layouts/images/KPIDefault-0.GIF";
                                               drow1[2] = itemsGreen.Count.ToString();
                                           }


No comments:

Post a Comment

Followers