[SalesForce] System.LimitException: Too many code statements: 200001

Below is my code.

companyList = [
            Select a.Id,a.Name, a.Phone, a.Website, etc... From Account a
            Where a.RecordType.Name = 'Blah'
            ];
String csvString = '';
        for(Account company : companyList)
        {
            csvString += myUtil.formatCSVString(company.Id) + ','
                        + myUtil.formatCSVString(company.Name) + ','
                        + myUtil.formatCSVString(company.Phone) + ','
                        etc...
                        ;

        }

How can I solve this error?

I am not doing any insert or update. I am just only select the data and want to do necessary thing.

More..
I use

1.Use SOQL for loop. Still error.

  1. I can't put the code in future call. As I want string return back form that method.

3.for limitation the of filters, I already use in SOQL statement by using WHERE.

The way I want to do is below.
1) I will query with Where condition from DB.
2) for each record, I need to parse its data by calling my helper method which will return String.
3) for each return string, I will append to CSVstring.

How can I achieve without hitting limitation.
I know it is really simple to write in Java, Now I am stuck on this simple loop.

Best Answer

Creating really big .csv files is a challenge without leveraging the async framework. Try to reduce the calls to that formatCSVString(), or perhaps refactor is such that you only need to call it once per line, rather than one per field.

I second Sdry's point, you may have to break this up into smaller chunks and only process, say, 2000 records at a time. Alternatively, going to the async framework, either through a @future method or a batch job, will get you a limit of 1,000,000 code statements per execution context.

After you construct this .csv string, what are you going to do with it? Can you explain the full use case, end to end, in more detail? What starts off this process and what is the end result?