You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用字符串查询按月过滤,优化Apex中员工生日筛选代码

优化方案

你有两种易维护的实现方式,无需每月修改代码调整参数:

方案1:静态SOQL直接调用系统时间(最优,无注入风险)

不需要改用动态字符串查询,直接在SOQL中取当前系统日期的月份即可,代码简洁且安全:

public static List<FB_Employees__c> getRecords() {
    return [
        SELECT Name, Date_of_birth__c
        FROM FB_Employees__c
        WHERE CALENDAR_MONTH(Date_of_birth__c) = CALENDAR_MONTH(System.today())
    ];
}

如果需要支持灵活指定查询月份,可以给方法增加入参,扩展性更强:

public static List<FB_Employees__c> getRecords(Integer targetMonth) {
    // 非法参数校验,避免传入1-12范围外的数值
    if(targetMonth == null || targetMonth < 1 || targetMonth > 12) {
        targetMonth = CALENDAR_MONTH(System.today());
    }
    return [
        SELECT Name, Date_of_birth__c
        FROM FB_Employees__c
        WHERE CALENDAR_MONTH(Date_of_birth__c) = :targetMonth
    ];
}

方案2:动态字符串SOQL实现(符合你提到的字符串查询需求)

如果确实需要通过动态拼接的方式实现,推荐使用变量绑定避免SOQL注入风险,代码如下:

public static List<FB_Employees__c> getRecords() {
    Integer currentMonth = CALENDAR_MONTH(System.today());
    String soql = 'SELECT Name, Date_of_birth__c FROM FB_Employees__c WHERE CALENDAR_MONTH(Date_of_birth__c) = :currentMonth';
    return Database.query(soql);
}

如果要支持指定月份查询,把currentMonth调整为方法入参传入即可。

内容的提问来源于stack exchange,提问作者aaron_le

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 11:51:00