You are on page 1of 23

Fetch XML in Microsoft

Dynamics 365
FetchXML is a XML based query language used in Microsoft Dynamics 365 CRM to fetch data. FetchXML is
capable of doing many things as explained below.

 Can only be used to retrieve data not able to perform CUD (Create/Update/Delete) operation.

 Can be used in JavaScript to retrieve data in client side also used in server side code to retrieve data.

 Can perform Aggregations such


as Sum, Average, Minimum, Maximum, Count(*), Count(attributename).

 Supports Linked entity data retrieval with conditions, filters, GroupBy, Sorting

 Can fetch 5000 record data at a time and supports paging concept to fetch more records page by page.

 Can be saved in user query entity as user owned view and saved query entity as organization owned
view.

 Can also be used in SSRS query in Reporting.

 Supports aliased name for attributes retrieved.

 Supports similar query capabilities as query expressions.

 Can be executed by using the RetrieveMultiple method.

 Can be downloaded/saved from Advance Find query.

Here is a list of sample FetchXML Queries given below.

Every day we use fetchXML in development. So here i have given a list of ready-made fetchXMLs which
you can use by modifying the code as per your business requirement. FetchXML query should validated
by the xsd schema.
Retrieve all attributes of account entity
<fetch
mapping=’logical’>

<entity
name=’account’>

<all-attributes/>

</entity>

</fetch>

Retrieve selected attributes of account entity


<fetch
mapping=’logical’>

<entity
name=’account’>

<attribute
name=’accountid’/>

<attribute
name=’name’/>

</entity>

</fetch>

Retrieve records of account entity with filter condition


<fetch
mapping=’logical’>

<entity
name=’account’>

<attribute
name=’accountid’/>

<attribute
name=’name’/>
<filter
type=’and’>

<condition
attribute=’name’
operator=’ne’
value=’Softchief’
/>

</filter>

</entity>

</fetch>

Retrieve contract records using linkedentity with customer using filter


condition in linked entity
<fetch
mapping=’logical’>

<entity
name=’contract’>

<attribute
name=’title’/>

<attribute
name=’customerid’/>

<link-entity
name=’contact’
from=’contactid’
to=’customerid’>

<filter
type=’and’>

<condition
attribute=’lastname’
operator=’eq’
value=’Pradhan’
/>

</filter>
</link-entity>

</entity>

</fetch>

Limit the Maximum (Lets Say 5)Number Of Records to be retrieved in


contact entity.
<fetch
mapping=’logical’
count=’5′>

<entity
name=’contact’>

<attribute
name=’name’
/>

</entity>

</fetch>

Limit the Maximum (Lets Say 5)Number Of Records to be retrieved in


contact entity.
<fetch
mapping=’logical’
count=’5′>

<entity
name=’contact’>

<attribute
name=’name’
/>

<attribute
name=’lastname’
/>

</entity>

</fetch>
Use of Inner Join in FetchXML
<fetch
version=’1.0′
mapping=’logical’
distinct=’false’>

<entity
name=’contact’>

<attribute
name=’fullname’/>

<link-entity
name=’account’
to=’parentcustomerid’
from=’accountid’
link-type=’inner’>

<attribute
name=’name’/>

</link-entity>

</entity>

</fetch>

Use of Left Outer Join in FetchXML


<fetch
mapping=’logical’>

<entity
name=’account’>

<attribute
name=’name’
/>

<link-entity
name=’lead’
from=’leadid’
to=’originatingleadid’
link-type=’outer’
/>
<filter
type=’and’>

<condition
entityname=’lead’
attribute=’leadid’
operator=’null’
/>

</filter>

</entity>

</fetch>

Use Avarage Aggregate in FetchXML


<fetch
distinct=’false’
mapping=’logical’
aggregate=’true’>

<entity
name=’opportunity’>

<attribute
name=’estimatedvalue’
alias=’estimatedvalue_avg’
aggregate=’avg’
/>

</entity>

</fetch>

Count No. of records retrieved in FetchXML


<fetch
distinct=’false’
mapping=’logical’
aggregate=’true’>

<entity
name=’opportunity’>

<attribute
name=’name’
alias=’opportunity_count’
aggregate=’count’/>

</entity>

</fetch>

Using “older than” clauses for date and time values in FetchXML Query
<fetch>

<entity
name=”incident”>

<attribute
name=”title”
/>

<attribute
name=”ticketnumber”
/>

<attribute
name=”createdon”
/>

<attribute
name=”incidentid”
/>

<filter
type=”and”>

<condition
attribute=”createdon”
operator=”olderthan-x-minutes”
value=”40″
/>

</filter>

</entity>

</fetch>

fiscal-period FetchXML Query


<fetch
aggregate=”true”>

<entity
name=”order”>

<attribute
name=”totalamount”
aggregate=”sum”
alias=”total”/>

<attribute
name=”datefulfilled”
groupby=”true”
dategrouping=”fiscal-period”/>

</entity>

</fetch>

Order by in FetchXML Query


<fetch
distinct=’false’
mapping=’logical’
aggregate=’true’>

<entity
name=’opportunity’>

<attribute
name=’opportunityid’
alias=’opportunity_count’
aggregate=’count’/>

<attribute
name=’estimatedvalue’
alias=’estimatedvalue_sum’
aggregate=’sum’/>

<attribute
name=’estimatedvalue’
alias=’estimatedvalue_avg’
aggregate=’avg’/>

<attribute
name=’actualclosedate’
groupby=’true’
dategrouping=’quarter’
alias=’quarter’
/>

<attribute
name=’actualclosedate’
groupby=’true’
dategrouping=’year’
alias=’year’
/>

<order
alias=’year’
descending=’false’
/>

<order
alias=’quarter’
descending=’false’
/>

<filter
type=’and’>

<condition
attribute=’statecode’
operator=’eq’
value=’Won’
/>

</filter>

</entity>

</fetch>

Order by in FetchXML Query


<fetch
distinct=’false’
mapping=’logical’
aggregate=’true’>

<entity
name=’opportunity’>

<attribute
name=’opportunityid’
alias=’opportunity_count’
aggregate=’count’/>

<attribute
name=’estimatedvalue’
alias=’estimatedvalue_sum’
aggregate=’sum’/>

<attribute
name=’estimatedvalue’
alias=’estimatedvalue_avg’
aggregate=’avg’/>

<attribute
name=’actualclosedate’
groupby=’true’
dategrouping=’quarter’
alias=’quarter’
/>

<attribute
name=’actualclosedate’
groupby=’true’
dategrouping=’year’
alias=’year’
/>

<order
alias=’year’
descending=’false’
/>

<order
alias=’quarter’
descending=’false’
/>

<filter
type=’and’>

<condition
attribute=’statecode’
operator=’eq’
value=’Won’
/>

</filter>
</entity>

</fetch>

List of Operators used in FetchXML are given below.

FetchXML
Operator ConditionOperator Description

The string occurs at the beginning of


like BeginsWith another string.

between Between The value is between two values.

like Contains The string contains another string.

The string does not begin with another


not-like DoesNotBeginWith string.

The string does not contain another


not-like DoesNotContain string.

The string does not end with another


not-like DoesNotEndWith string.

like EndsWith The string ends with another string.

eq Equal The values are compared for equality.

The value is equal to the specified


eq-businessid EqualBusinessId business ID.

The value is equal to the specified user


eq-userid EqualUserId ID.

The record is owned by teams that the


eq-userteams EqualUserTeams user is a member of.
The value is greater than or equal to the
ge GreaterEqual compared value.

The value is greater than the compared


gt GreaterThan value.

in In TheThe value exists in a list of values.

The value is within the specified fiscal


in-fiscal-period InFiscalPeriod period.

in-fiscal-period- The value is within the specified fiscal


and-year InFiscalPeriodAndYear period and year.

in-fiscal-year InFiscalYear The value is within the specified year.

in-or-after-fiscal- The value is within or after the specified


period-and-year InOrAfterFiscalPeriodAndYear fiscal period and year.

in-or-before-fiscal- The value is within or before the


period-and-year InOrBeforeFiscalPeriodAndYear specified fiscal period and year.

The value is within the last seven days


last-seven-days Last7Days including today.

last-fiscal-period LastFiscalPeriod The value is within the last fiscal period.

last-fiscal-year LastFiscalYear The value is within the last fiscal year.

The value is within the last month


including first day of the last month and
last-month LastMonth last day of the last month.

The value is within the previous week


last-week LastWeek including Sunday through Saturday.

last-x-days LastXDays The value is within last X days.


last-x-fiscal- The value is within the last X (specified
periods LastXFiscalPeriods value) fiscal periods.

The value is within the last X (specified


last-x-fiscal-years LastXFiscalYears value) fiscal periods.

last-x-hours LastXHours The value is within the last X hours.

The value is within the last X (specified


last-x-months LastXMonths value) months.

The value is within the last X (specified


last-x-weeks LastXWeeks value) weeks.

last-x-years LastXYears The value is within the last X years.

last-year LastYear The value is within the previous year.

The value is less than or equal to the


le LessEqual compared value.

The value is less than the compared


lt LessThan value.

The character string is matched to the


like Like specified pattern.

next-seven-days Next7Days The value is within the next seven days.

The value is within the next fiscal


next-fiscal-period NextFiscalPeriod period.

next-fiscal-year NextFiscalYear The value is within the next fiscal year.

next-month NextMonth The value is within the next month.

next-week NextWeek The value is within the next week.


The value is within the next X (specified
next-x-days NextXDays value) days.

next-x-fiscal- The value is within the next X (specified


periods NextXFiscalPeriods value) fiscal period.

The value is within the next X (specified


next-x-fiscal-years NextXFiscalYears value) fiscal years.

The value is within the next X (specified


next-x-hours NextXHours value) hours.

The value is within the next X (specified


next-x-months NextXMonths value) months.

next-x-weeks NextXWeeks The value is within the next X weeks.

next-x-years NextXYears The value is within the next X years.

next-year NextYear The value is within the next year.

not-between NotBetween The value is not between two values.

ne NotEqual The two values are not equal.

The value is not equal to the specified


ne-businessid NotEqualBusinessId business ID.

The value is not equal to the specified


ne-userid NotEqualUserId user ID.

The given value is not matched to a value


not-in NotIn in a subquery or a list.

The character string does not match the


not-like NotLike specified pattern.
not-null NotNull The value is not null.

ne NotOn The value is not on the specified date.

null Null The value is null.

olderthan-x- The value is older than the specified


months OlderThanXMonths number of months.

on On The value is on a specified date.

on-or-after OnOrAfter The value is on or after a specified date.

The value is on or before a specified


on-or-before OnOrBefore date.

The value is within the current fiscal


this-fiscal-period ThisFiscalPeriod period.

The value is within the current fiscal


this-fiscal-year ThisFiscalYear year.

this-month ThisMonth The value is within the current month.

this-week ThisWeek The value is within the current week.

this-year ThisYear The value is within the current year.

today Today The value equals today’s date.

tomorrow Tomorrow The value equals tomorrow’s date.

yesterday Yesterday The value equals yesterday’s date.

List of older than clauses in a FetchXML expression


Older than X minutes

Older than X hours

Older than X days

Older than X weeks

Older than X months

Older than X years

How to Retrieve Data using Fetch XML in server side (Sample given below)
// Retrieve all accounts owned by the user with read access rights to the accounts and

// where the last name of the user is not Cannon.

string varFetchXML = @”

<fetch
mapping=’logical’>

<entity
name=’account’>

<attribute
name=’accountid’/>

<attribute
name=’name’/>

<link-entity
name=’systemuser’
to=’owninguser’>

<filter
type=’and’>
<condition
attribute=’lastname’
operator=’ne’
value=’Cannon’
/>

</filter>

</link-entity>

</entity>

</fetch> “;

EntityCollection result =

_serviceProxy.RetrieveMultiple(new FetchExpression(varFetchXML));

foreach (var c in result.Entities)

System.Console.WriteLine(c.Attributes[“name”]);

How to Retrieve Data using Fetch XML in client side using


WebAPI(Sample given below)
var fetchXml =

“<fetch
version=’1.0′
output-format=’xml-platform’
mapping=’logical’
distinct=’false’>”+

“<entity
name=’account’>”+
“<attribute
name=’name’
/>”+

“<attribute
name=’primarycontactid’
/>”+

“<attribute
name=’telephone1′
/>”+

“<attribute
name=’accountid’
/>”+

“<order
attribute=’name’
descending=’false’
/>”+

“<filter
type=’and’>”+

“<condition
attribute=’name’
operator=’like’
value=’C%’
/>”+

“</filter>”+

“</entity>”+

“</fetch>”;

var encodedFetchXml = encodeURI(fetchXml);

var queryPath = “/api/data/v8.0/accounts?fetchXml=” + encodedFetchXml;

var requestPath = Xrm.Page.context.getClientUrl() + queryPath;


var req = new XMLHttpRequest();

req.open(“GET”, requestPath, true);

req.setRequestHeader(“Accept”, “application/json”);

req.setRequestHeader(“Content-Type”, “application/json; charset=utf-8”);

req.onreadystatechange = function ()

if (this.readyState === 4)

this.onreadystatechange = null;

if (this.status === 200)

var returned = JSON.parse(this.responseText);

var results = returned.value;

for (var i = 0; i < results.length; i++)

var accountName = results[i][“name”];

var primaryContactId = results[i][“_primarycontactid_value”];


var telephone = results[i][“telephone1”];

var accountId = results[i][“accountid”];

//TODO: Implement logic for handling results as desired

else

alert(this.statusText);

};

req.send();

How to Put Parameters in Fetch XML

string fetchNotifications = @”

<fetch version=’1.0′ output-format=’xml-platform’ mapping=’logical’ distinct=’false’>

<entity name=’new_notification’>

<attribute name=’new_notificationid’ />

<attribute name=’new_name’ />

<attribute name=’createdon’ />

<attribute name=’new_isread’ />

<order attribute=’new_name’ descending=’false’ />

<filter type=’and’>
<condition attribute=’new_contact’ operator=’eq’ value='”+ contactId + @”‘/>

</filter>

</entity>

</fetch> “;

Create a Detailed Report using Report Designer


To create a report

1. In Visual Studio, create or open a Report Server project. For more information,
see Create a Report Server Project.
2. On the Project menu, choose Add New Item.

The Add New Item dialog box appears.

3. Choose Report Wizard, and then choose Add.

The Report Wizard opens to the Select Data Source page.

4. Choose the TFS2010ReportDS shared data source, and then choose Next.

Even though you might have installed or upgraded to TFS 2013, these names,
which were assigned to the data sources for TFS 2010, are in use.

The wizard advances to the Design the Query page.

1. Choose Query Builder.

The Query Build dialog box appears.

To create the query that will retrieve the data for the report

1. Choose Generic Query Designer on the query builder toolbar to enable the query
designer.
2. Choose Add Table on the query builder toolbar.

The Add Table dialog box appears.

3. Choose the Current Work Item table, and then choose Add.
4. Choose the Work Item table, and then choose Add.
This table contains the Work Item dimension.

5. Choose the Person table, choose Add, and then click Close.

This table contains the Person dimension. The fact table for current work items has
foreign keys to this table for the Assigned To, Changed By, and Created By fields.

6. In the Work Item table, select the check boxes


for System_Title and System_State.
7. In the Person table, select the check box for Person.
8. In the query pane, delete the clauses that use Changed By and Created By so that
you now have the following query.

SQLCopy

SELECT Person.Person, [Work Item].System_State


FROM [Current Work Item] INNER JOIN
[Work Item] ON [Current Work Item].[Work Item] =
[Work Item].__ID INNER JOIN
Person ON [Current Work Item].[Assigned To] = Person.__ID

9. Choose Run on the query builder toolbar to verify that the query works, and then
choose OK.

The Query Builder is closed, and the Design the Query page of the Report
Wizard reappears.

To design the report layout

1. Choose Next.

The wizard advances to the Report Type page.

2. Choose Tabular, and then choose Next.

The wizard advances to the Design the Table page.

3. Choose System_Title, and then choose Details.


4. Choose Person, and then choose Details.
5. Choose System_State, choose Group, and then choose Next.

The wizard advances to the Choose the Table Layout page.


6. Choose the layout options that you prefer, and then choose Next.

The wizard advances to the Choose the Table Style page.

7. Choose any style, and then choose Next.

The wizard advances to the Completing the Report page.

8. Type a name for the report, choose Preview Report, and then choose Finish to
create the report.

The wizard closes, and the report document window appears with the Preview tab
active.

To deploy the report

1. In Solution Explorer, choose the report.


2. On the Build menu, choose Deploy ReportName.

To successfully deploy the report, your project settings must be set to appropriate
values. For more information, see Create a Report Server Project.

You might also like