I have a SQL like this in my apex code:
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) = 7
];
}
It will filter all the users who have birthday on July, by doing this way, I will have to change the code every month and I think I should have a another way to do it automatically, I think of a way using string query but I'm not still familiar with it? Can anyone suggest me an idea to improve the code?
You just want to filter those employees whose birthdays are in the present month ?
First get the month as an integer from the present date.
Then insert this value in your query using single quotes ('....') around your month value and treating the whole query as a single string.
public static list<FB_Employees__c> getRecords()
{
int thisMonth = Calendar.getInstance().get(Calendar.MONTH) + 1; // Since Java month range is 0..11
return [
"SELECT Name, Date_of_birth__c
FROM FB_Employees__c
WHERE CALENDAR_MONTH(Date_of_birth__c) = '" + thisMonth + "';"
];
}