0

Getting my feet wet on CAML. I was able to get a query that shows a count for a list. Now I need to do count based on multiple information.

Dog
Dog
Cat
Cat
Cat
fish
fish
fish
fish

Loops through and creates the following:

Dog: 2
Cat: 3
Fish: 4

So how would the Query look look? I'm thinking the below but this looks too cumbersome and repetative. Is there an easier way to have multiple WHERE clauses?

var dog = "<View><Query><Where><Eq><FieldRef Name='Pet' /><Value Type='Text'>Dog</Value></Eq></Where></Query><RowLimit>0</RowLimit></View>";
var cat = "<View><Query><Where><Eq><FieldRef Name='Pet' /><Value Type='Text'>Cat</Value></Eq></Where></Query><RowLimit>0</RowLimit></View>";
var fish= "<View><Query><Where><Eq><FieldRef Name='Pet' /><Value Type='Text'>fish</Value></Eq></Where></Query><RowLimit>0</RowLimit></View>";
1

You can't have multiple WHERE clauses in a single query, but there's nothing wrong with doing multiple queries sequentially.

If I understand correctly, your code works as expected but you want to reduce the repetitiveness of having three long query strings that are basically identical.

In that case, the solution is to create an array of keywords and map it to a function that produces the query strings.

var keywords = ["Dog", "Cat", "Fish"];

var makeQueryString = function (keyword) {
    return ["<View><Query><Where><Eq><FieldRef Name='Pet' /><Value Type='Text'>",
        keyword,
        "</Value></Eq></Where></Query><RowLimit>0</RowLimit></View>"
    ].join('')
}

keywords.map(makeQueryString);

// Results:
// [ '<View><Query><Where><Eq><FieldRef Name=\'Pet\' /><Value Type=\'Text\'>Dog</Value></Eq></Where></Query><RowLimit>0</RowLimit></View>',
//   '<View><Query><Where><Eq><FieldRef Name=\'Pet\' /><Value Type=\'Text\'>Cat</Value></Eq></Where></Query><RowLimit>0</RowLimit></View>',
//   '<View><Query><Where><Eq><FieldRef Name=\'Pet\' /><Value Type=\'Text\'>Fish</Value></Eq></Where></Query><RowLimit>0</RowLimit></View>' ]

From there you can use .map() again to actually invoke each query and handle the results, but that is outside the scope of this answer.

  • Thanks @chris-odegard. Worked perfectly and the code looks clean. Will investigate the .map(). – adams-j May 17 at 14:51

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.