如何用FetchXml运算符获取CRM中今日前11天创建的预约记录?
FetchXml 获取“今日减11天”创建的预约记录
嘿,这个需求其实很明确——要精准匹配当前日期往前推11天的整个自然日里创建的预约记录对吧?我来给你拆解下怎么用FetchXml实现:
核心思路
因为createdon字段是带时间戳的(比如2018-04-01 14:30:00),直接用eq运算符只会匹配到时间完全一致的记录,这显然不是你要的。我们需要锁定目标日期的全天范围:从目标日期的00:00:00到23:59:59。
推荐的运算符组合
你需要结合on-or-after和on-or-before两个运算符(或者用between,效果一致),配合FetchXml的日期函数addDays()来动态计算目标范围。
完整FetchXml代码示例
<fetch distinct="false" mapping="logical" output-format="xml-platform" version="1.0"> <entity name="appointment"> <attribute name="subject"/> <attribute name="statecode"/> <attribute name="createdon"/> <!-- 建议加上这个字段验证结果 --> <filter type="and"> <!-- 匹配目标日期的00:00:00及以后 --> <condition attribute="createdon" operator="on-or-after" value="addDays(utcnow(), -11, 0)"/> <!-- 匹配目标日期的23:59:59及以前 --> <condition attribute="createdon" operator="on-or-before" value="addDays(utcnow(), -10, -1)"/> </filter> </entity> </fetch>
代码解释
addDays(utcnow(), -11, 0):utcnow()取当前UTC时间,-11往前推11天,第三个参数0表示将时间截断到当天的起始时刻(00:00:00)。addDays(utcnow(), -10, -1):往前推10天,再减去1秒,得到的就是目标日期的结束时刻(23:59:59),完美覆盖全天的所有时间点。
简化写法(用between运算符)
如果觉得两个条件太啰嗦,也可以用between运算符一次性指定范围:
<fetch distinct="false" mapping="logical" output-format="xml-platform" version="1.0"> <entity name="appointment"> <attribute name="subject"/> <attribute name="statecode"/> <attribute name="createdon"/> <filter type="and"> <condition attribute="createdon" operator="between"> <value>addDays(utcnow(), -11, 0)</value> <value>addDays(utcnow(), -10, -1)</value> </condition> </filter> </entity> </fetch>
注意事项
- 因为Dynamics 365中日期字段默认存储UTC时间,所以用
utcnow()是标准做法。如果你的业务需要基于本地时区计算,需要额外调整时间转换逻辑,但大部分场景下UTC就足够了。
内容的提问来源于stack exchange,提问作者Oscar Dominguez Navarrete
相关产品推荐
相关产品推荐

