[SalesForce] Need to build the dynamic soql query in trigger

custom object: schedule_c
fields: Runway
_C and date_C
Runway
_c is a picklist field having track1 and track2 values.
date__c field is datetime field.

i having the the records in schedule object
e.g airline: kingfisher
flight k-101
runway: track1
date: 22-02-2014 11.00 AM

the same records like above…now i created one trigger to prevent the same
schedule to insert.i used .adderror to show the validation error while
inserting and updating new record.

trigger is working but if i having suppose million of existing records and
also want to insert or update the thousands of records,
I need to use dynamic soql query…here what i created trigger and soql query…

**trigger:** 
 trigger newrunway on Schedule__c (before insert, before update) {
 set<DateTime> Date = new set<DateTime>();
 set<id> Runway = new set<id>();

for ( Schedule__c sch : trigger.new){
  Date.add(sch.Date__c);
  Runway.add(sch.Runway__c);

}  

**string dynamicQuery = 'Select Id,date__c,Runway__c From Schedule__c 
   WHERE     Runway__c  IN :runwayids and  Date__c IN :Dateids';
   List<Schedule__c> schedule = Database.query(dynamicQuery);**


    if (schedule.size() > 0) {
        sch.addError('Flight Already Scheduled on the Runway');

    }
    }

above i created the dynamic query but it seems wrong (problem in logic of query)
and need to change…could u help me in this to make it correct

Best Answer

As @Birthus mentioned a trigger will only work for this assuming you have less than 50k records in the DB. You can try to further filter your SOQL, but beyond that Batch may be the way to go.

Assuming that you have less than 50k records, then something like below should work, but will not work should you have a large number of Schedule__c records in the database already

trigger newrunway on Schedule__c (before insert, before update) {

    map<string,set<DateTime>> runway2DateMap = new map<string,set<DateTime>>();

    for(Schedule__c sched : [Select Id, Date__c, Runway__c From Schedule__c Where Date__c > TODAY And Id Not In : trigger.new]){
        if(!runway2DateMap.containsKey(sched.Runway__c)){
            runway2DateMap.put(sched.Runway__c, new set<DateTime>());
        }
        runway2DateMap.get(sched.Runway__c).add(sched.Date__c);
    }

    for(Schedule__c sched : trigger.new){
        if(runway2DateMap.get(sched.Runway__c).contains(sched.Date__c)){
            sched.addError('Flight Already Scheduled on the Runway');
        }
    } 
}