3

I'm trying to retrieve a list of items where a specific field matches a specific value. Here's what my CAML query:

                    Query query = new SPQuery();
                    SPQuery query2014 = new SPQuery();
                    query2014.Query = @"<Query><Where><Eq><FieldRef Name='Year' /><Value Type='Text'>" + 2014 + "</Value></Eq></Where></Query>";

                    SPListItemCollection Items2014 = list.GetItems(query2014);
                    if (Items2014.Count == 0 )
                    {
                        SPListItem Item2 = list.Items.Add();
                        Item2["Year"] = "2014";
                        Item2.Update();
                    }
  • You are missing an <And> after your where. – Bunzab May 1 '15 at 22:46
  • Why Add <And>?? – Engy May 1 '15 at 22:51
  • There should be no <And> just remove the <Query> attributes and you will be fine – Robert Lindgren May 2 '15 at 11:07
1

Your code looks like you are using server object model using c#.

I have faced issues using CAML queries. My queries were not able to pull data, But after removing <Query></Query> tag I was able to solve the problem.

So based on my past experience I can propose you following improvements and try the below code.

Query query = new SPQuery();
                SPQuery query2014 = new SPQuery();
                query2014.Query = @"<Where><Eq><FieldRef Name='Year' /><Value Type='Text'>" + 2014 + "</Value></Eq></Where>";

                SPListItemCollection Items2014 = list.GetItems(query2014);
                if (Items2014.Count == 0 )
                {
                    SPListItem Item2 = list.Items.Add();
                    Item2["Year"] = "2014";
                    Item2.Update();
                }
0

This has something to do with your SPQuery and if you pass an invalid one. When SharePoint parse the XML and detected it is invalid it passes instead of your default query a CAML Query that looks like this.

<Query>
    <Where>
        <Neq>
            <FieldRef Name='ID' />
            <Value Type='Integer'>-1</Value>
        </Neq>
    </Where>
</Query>

So this query will return all the items.

0

Check if a ListItem exists using CAML

SPQuery spQuery = new SPQuery();
spQuery.Query = @"<Where><Eq><FieldRef Name='Year' /><Value Type='Text'>2014</Value></Eq></Where>";

if (list.GetItems(spQuery).Count == 0)
{
    SPListItem item = list.Items.Add();
    item["Year"] = "2014";
    item.Update();
}

Check if a ListItem exists using LINQ

if(list.Items.OfType<SPListItem>().Any(i => i["Year"] == "2014"))
{
    SPListItem item = list.Items.Add();
    item["Year"] = "2014";
    item.Update();
}

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.