Convert string to query

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;







up vote
0
down vote

favorite












Can anyone help me on how to convert the String q1 into a query? I am trying to put my variable 'q1' inside the but I always got an error "Unexpected token q1"



Heres the code.



String q1 = 'SELECT count() FROM Case WHERE '+q;
Integer totalCount = 0;
totalCount = [q1];



public Case getCases() 

Map<Id, BusinessProcess> bp = new Map<Id, BusinessProcess>([SELECT Id FROM BusinessProcess WHERE Name IN ('MSP', 'Provisioning', 'On-Boarding')]);

Map<Id, RecordType> r = new Map<Id, RecordType>([SELECT Id, Name FROM RecordType WHERE SObjectType = 'Case' AND BusinessProcessId IN :bp.keySet()]);

String q = '';
if (view.startsWith('all'))
q += 'AccountId = :acctId';
else
q += 'ContactId = :conId';

if (view.endsWith('closed'))
q += ' AND IsClosed = true';
else
q += ' AND IsClosed = false';

if (view == 'waiting')
q += ' AND Status = 'Awaiting Customer Response'';

if (String.isNotBlank(query))
q += ' AND (Subject LIKE '%'+query+'%' OR Product__c LIKE '%'+query+'%' OR CaseNumber LIKE '%'+query+'%' OR Product__c LIKE '%'+query+'%' OR Case_Type__c LIKE '%'+query+'%' OR MaxDeviceName__c LIKE '%'+query+'%' OR Device_Name__C LIKE '%'+query+'%' OR N_Central_Server__c LIKE '%'+query+'%')';

if(!r.isEmpty())
Set<Id> recordTypeSet = r.keySet();
q += ' AND RecordTypeId IN :recordTypeSet';


String queryFields = 'Id, Priority';
for (Schema.FieldSetMember field : getFields())
queryFields += ',' + field.getFieldPath();

if (selectedPage != '0') counter = list_size*integer.valueOf(selectedPage)-list_size;

if(String.isBlank(sortOrder) && String.isBlank(sortField))
q = 'SELECT '+queryFields+' FROM Case WHERE ' + q + ' ORDER BY CaseNumber DESC limit '+list_size+' offset '+counter;


else
q = 'SELECT '+queryFields+' FROM Case WHERE ' + q + ' ORDER BY ' + sortField + ' ' + sortOrder + ' limit '+list_size+' offset '+counter;


String q1='SELECT count() FROM Case WHERE '+q;

Integer totalCount =[q1];


Case cases = Database.query(q);

for (Case cs : cases)

if (!productUtil.containsKey(cs.Product__c))
productUtil.put(cs.Product__c,cs.Product__c);


return cases;









share|improve this question



























    up vote
    0
    down vote

    favorite












    Can anyone help me on how to convert the String q1 into a query? I am trying to put my variable 'q1' inside the but I always got an error "Unexpected token q1"



    Heres the code.



    String q1 = 'SELECT count() FROM Case WHERE '+q;
    Integer totalCount = 0;
    totalCount = [q1];



    public Case getCases() 

    Map<Id, BusinessProcess> bp = new Map<Id, BusinessProcess>([SELECT Id FROM BusinessProcess WHERE Name IN ('MSP', 'Provisioning', 'On-Boarding')]);

    Map<Id, RecordType> r = new Map<Id, RecordType>([SELECT Id, Name FROM RecordType WHERE SObjectType = 'Case' AND BusinessProcessId IN :bp.keySet()]);

    String q = '';
    if (view.startsWith('all'))
    q += 'AccountId = :acctId';
    else
    q += 'ContactId = :conId';

    if (view.endsWith('closed'))
    q += ' AND IsClosed = true';
    else
    q += ' AND IsClosed = false';

    if (view == 'waiting')
    q += ' AND Status = 'Awaiting Customer Response'';

    if (String.isNotBlank(query))
    q += ' AND (Subject LIKE '%'+query+'%' OR Product__c LIKE '%'+query+'%' OR CaseNumber LIKE '%'+query+'%' OR Product__c LIKE '%'+query+'%' OR Case_Type__c LIKE '%'+query+'%' OR MaxDeviceName__c LIKE '%'+query+'%' OR Device_Name__C LIKE '%'+query+'%' OR N_Central_Server__c LIKE '%'+query+'%')';

    if(!r.isEmpty())
    Set<Id> recordTypeSet = r.keySet();
    q += ' AND RecordTypeId IN :recordTypeSet';


    String queryFields = 'Id, Priority';
    for (Schema.FieldSetMember field : getFields())
    queryFields += ',' + field.getFieldPath();

    if (selectedPage != '0') counter = list_size*integer.valueOf(selectedPage)-list_size;

    if(String.isBlank(sortOrder) && String.isBlank(sortField))
    q = 'SELECT '+queryFields+' FROM Case WHERE ' + q + ' ORDER BY CaseNumber DESC limit '+list_size+' offset '+counter;


    else
    q = 'SELECT '+queryFields+' FROM Case WHERE ' + q + ' ORDER BY ' + sortField + ' ' + sortOrder + ' limit '+list_size+' offset '+counter;


    String q1='SELECT count() FROM Case WHERE '+q;

    Integer totalCount =[q1];


    Case cases = Database.query(q);

    for (Case cs : cases)

    if (!productUtil.containsKey(cs.Product__c))
    productUtil.put(cs.Product__c,cs.Product__c);


    return cases;









    share|improve this question























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      Can anyone help me on how to convert the String q1 into a query? I am trying to put my variable 'q1' inside the but I always got an error "Unexpected token q1"



      Heres the code.



      String q1 = 'SELECT count() FROM Case WHERE '+q;
      Integer totalCount = 0;
      totalCount = [q1];



      public Case getCases() 

      Map<Id, BusinessProcess> bp = new Map<Id, BusinessProcess>([SELECT Id FROM BusinessProcess WHERE Name IN ('MSP', 'Provisioning', 'On-Boarding')]);

      Map<Id, RecordType> r = new Map<Id, RecordType>([SELECT Id, Name FROM RecordType WHERE SObjectType = 'Case' AND BusinessProcessId IN :bp.keySet()]);

      String q = '';
      if (view.startsWith('all'))
      q += 'AccountId = :acctId';
      else
      q += 'ContactId = :conId';

      if (view.endsWith('closed'))
      q += ' AND IsClosed = true';
      else
      q += ' AND IsClosed = false';

      if (view == 'waiting')
      q += ' AND Status = 'Awaiting Customer Response'';

      if (String.isNotBlank(query))
      q += ' AND (Subject LIKE '%'+query+'%' OR Product__c LIKE '%'+query+'%' OR CaseNumber LIKE '%'+query+'%' OR Product__c LIKE '%'+query+'%' OR Case_Type__c LIKE '%'+query+'%' OR MaxDeviceName__c LIKE '%'+query+'%' OR Device_Name__C LIKE '%'+query+'%' OR N_Central_Server__c LIKE '%'+query+'%')';

      if(!r.isEmpty())
      Set<Id> recordTypeSet = r.keySet();
      q += ' AND RecordTypeId IN :recordTypeSet';


      String queryFields = 'Id, Priority';
      for (Schema.FieldSetMember field : getFields())
      queryFields += ',' + field.getFieldPath();

      if (selectedPage != '0') counter = list_size*integer.valueOf(selectedPage)-list_size;

      if(String.isBlank(sortOrder) && String.isBlank(sortField))
      q = 'SELECT '+queryFields+' FROM Case WHERE ' + q + ' ORDER BY CaseNumber DESC limit '+list_size+' offset '+counter;


      else
      q = 'SELECT '+queryFields+' FROM Case WHERE ' + q + ' ORDER BY ' + sortField + ' ' + sortOrder + ' limit '+list_size+' offset '+counter;


      String q1='SELECT count() FROM Case WHERE '+q;

      Integer totalCount =[q1];


      Case cases = Database.query(q);

      for (Case cs : cases)

      if (!productUtil.containsKey(cs.Product__c))
      productUtil.put(cs.Product__c,cs.Product__c);


      return cases;









      share|improve this question













      Can anyone help me on how to convert the String q1 into a query? I am trying to put my variable 'q1' inside the but I always got an error "Unexpected token q1"



      Heres the code.



      String q1 = 'SELECT count() FROM Case WHERE '+q;
      Integer totalCount = 0;
      totalCount = [q1];



      public Case getCases() 

      Map<Id, BusinessProcess> bp = new Map<Id, BusinessProcess>([SELECT Id FROM BusinessProcess WHERE Name IN ('MSP', 'Provisioning', 'On-Boarding')]);

      Map<Id, RecordType> r = new Map<Id, RecordType>([SELECT Id, Name FROM RecordType WHERE SObjectType = 'Case' AND BusinessProcessId IN :bp.keySet()]);

      String q = '';
      if (view.startsWith('all'))
      q += 'AccountId = :acctId';
      else
      q += 'ContactId = :conId';

      if (view.endsWith('closed'))
      q += ' AND IsClosed = true';
      else
      q += ' AND IsClosed = false';

      if (view == 'waiting')
      q += ' AND Status = 'Awaiting Customer Response'';

      if (String.isNotBlank(query))
      q += ' AND (Subject LIKE '%'+query+'%' OR Product__c LIKE '%'+query+'%' OR CaseNumber LIKE '%'+query+'%' OR Product__c LIKE '%'+query+'%' OR Case_Type__c LIKE '%'+query+'%' OR MaxDeviceName__c LIKE '%'+query+'%' OR Device_Name__C LIKE '%'+query+'%' OR N_Central_Server__c LIKE '%'+query+'%')';

      if(!r.isEmpty())
      Set<Id> recordTypeSet = r.keySet();
      q += ' AND RecordTypeId IN :recordTypeSet';


      String queryFields = 'Id, Priority';
      for (Schema.FieldSetMember field : getFields())
      queryFields += ',' + field.getFieldPath();

      if (selectedPage != '0') counter = list_size*integer.valueOf(selectedPage)-list_size;

      if(String.isBlank(sortOrder) && String.isBlank(sortField))
      q = 'SELECT '+queryFields+' FROM Case WHERE ' + q + ' ORDER BY CaseNumber DESC limit '+list_size+' offset '+counter;


      else
      q = 'SELECT '+queryFields+' FROM Case WHERE ' + q + ' ORDER BY ' + sortField + ' ' + sortOrder + ' limit '+list_size+' offset '+counter;


      String q1='SELECT count() FROM Case WHERE '+q;

      Integer totalCount =[q1];


      Case cases = Database.query(q);

      for (Case cs : cases)

      if (!productUtil.containsKey(cs.Product__c))
      productUtil.put(cs.Product__c,cs.Product__c);


      return cases;











      share|improve this question












      share|improve this question




      share|improve this question








      edited Aug 6 at 9:14
























      asked Aug 6 at 8:42









      Mike De Villa

      66




      66




















          4 Answers
          4






          active

          oldest

          votes

















          up vote
          6
          down vote



          accepted










          Normally you could just use Database.query(queryString) to make a query from a string.



          However, that method only returns a List<SObject> that cannot be cast to a Integer. Since you are looking for a count() you need to use Database.countQuery().



          String q1 = 'SELECT count() FROM Case WHERE '+q;
          Integer totalCount = Database.countQuery(q1);





          share|improve this answer




























            up vote
            1
            down vote













            If you want to build dynamic WHERE clause read this article: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_dynamic_soql.htm



            But Database.query(str) will produce a list of sObjects as a result. So you should save this to an list or execute .size() on the query method.






            share|improve this answer




























              up vote
              -1
              down vote













              String soql = 'SELECT count(id) FROM Case ';
              soql = soql +' where your Condition';
              database.query(soql);


              This will query your string.






              share|improve this answer

















              • 1




                Suggest you mention the need to avoid the risk of SOQL Injection too.
                – Keith C
                Aug 6 at 9:01

















              up vote
              -2
              down vote













              As per your query it's returning integer value i.e. Count always should be an integer.



              Integer q1 = 'SELECT count() FROM Case WHERE '+q;


              It would be great if you are explaining bit more on below code.



              totalCount = [q1]; - I believe, this is not a correct syntax






              share|improve this answer





















                Your Answer







                StackExchange.ready(function()
                var channelOptions =
                tags: "".split(" "),
                id: "459"
                ;
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function()
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled)
                StackExchange.using("snippets", function()
                createEditor();
                );

                else
                createEditor();

                );

                function createEditor()
                StackExchange.prepareEditor(
                heartbeatType: 'answer',
                convertImagesToLinks: false,
                noModals: false,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: null,
                bindNavPrevention: true,
                postfix: "",
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                );



                );








                 

                draft saved


                draft discarded


















                StackExchange.ready(
                function ()
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsalesforce.stackexchange.com%2fquestions%2f227848%2fconvert-string-to-query%23new-answer', 'question_page');

                );

                Post as a guest






























                4 Answers
                4






                active

                oldest

                votes








                4 Answers
                4






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes








                up vote
                6
                down vote



                accepted










                Normally you could just use Database.query(queryString) to make a query from a string.



                However, that method only returns a List<SObject> that cannot be cast to a Integer. Since you are looking for a count() you need to use Database.countQuery().



                String q1 = 'SELECT count() FROM Case WHERE '+q;
                Integer totalCount = Database.countQuery(q1);





                share|improve this answer

























                  up vote
                  6
                  down vote



                  accepted










                  Normally you could just use Database.query(queryString) to make a query from a string.



                  However, that method only returns a List<SObject> that cannot be cast to a Integer. Since you are looking for a count() you need to use Database.countQuery().



                  String q1 = 'SELECT count() FROM Case WHERE '+q;
                  Integer totalCount = Database.countQuery(q1);





                  share|improve this answer























                    up vote
                    6
                    down vote



                    accepted







                    up vote
                    6
                    down vote



                    accepted






                    Normally you could just use Database.query(queryString) to make a query from a string.



                    However, that method only returns a List<SObject> that cannot be cast to a Integer. Since you are looking for a count() you need to use Database.countQuery().



                    String q1 = 'SELECT count() FROM Case WHERE '+q;
                    Integer totalCount = Database.countQuery(q1);





                    share|improve this answer













                    Normally you could just use Database.query(queryString) to make a query from a string.



                    However, that method only returns a List<SObject> that cannot be cast to a Integer. Since you are looking for a count() you need to use Database.countQuery().



                    String q1 = 'SELECT count() FROM Case WHERE '+q;
                    Integer totalCount = Database.countQuery(q1);






                    share|improve this answer













                    share|improve this answer



                    share|improve this answer











                    answered Aug 6 at 9:11









                    Fernando Gavinho

                    3,001927




                    3,001927






















                        up vote
                        1
                        down vote













                        If you want to build dynamic WHERE clause read this article: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_dynamic_soql.htm



                        But Database.query(str) will produce a list of sObjects as a result. So you should save this to an list or execute .size() on the query method.






                        share|improve this answer

























                          up vote
                          1
                          down vote













                          If you want to build dynamic WHERE clause read this article: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_dynamic_soql.htm



                          But Database.query(str) will produce a list of sObjects as a result. So you should save this to an list or execute .size() on the query method.






                          share|improve this answer























                            up vote
                            1
                            down vote










                            up vote
                            1
                            down vote









                            If you want to build dynamic WHERE clause read this article: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_dynamic_soql.htm



                            But Database.query(str) will produce a list of sObjects as a result. So you should save this to an list or execute .size() on the query method.






                            share|improve this answer













                            If you want to build dynamic WHERE clause read this article: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_dynamic_soql.htm



                            But Database.query(str) will produce a list of sObjects as a result. So you should save this to an list or execute .size() on the query method.







                            share|improve this answer













                            share|improve this answer



                            share|improve this answer











                            answered Aug 6 at 8:54









                            mth0

                            111




                            111




















                                up vote
                                -1
                                down vote













                                String soql = 'SELECT count(id) FROM Case ';
                                soql = soql +' where your Condition';
                                database.query(soql);


                                This will query your string.






                                share|improve this answer

















                                • 1




                                  Suggest you mention the need to avoid the risk of SOQL Injection too.
                                  – Keith C
                                  Aug 6 at 9:01














                                up vote
                                -1
                                down vote













                                String soql = 'SELECT count(id) FROM Case ';
                                soql = soql +' where your Condition';
                                database.query(soql);


                                This will query your string.






                                share|improve this answer

















                                • 1




                                  Suggest you mention the need to avoid the risk of SOQL Injection too.
                                  – Keith C
                                  Aug 6 at 9:01












                                up vote
                                -1
                                down vote










                                up vote
                                -1
                                down vote









                                String soql = 'SELECT count(id) FROM Case ';
                                soql = soql +' where your Condition';
                                database.query(soql);


                                This will query your string.






                                share|improve this answer













                                String soql = 'SELECT count(id) FROM Case ';
                                soql = soql +' where your Condition';
                                database.query(soql);


                                This will query your string.







                                share|improve this answer













                                share|improve this answer



                                share|improve this answer











                                answered Aug 6 at 8:52









                                sanket kumar

                                47412




                                47412







                                • 1




                                  Suggest you mention the need to avoid the risk of SOQL Injection too.
                                  – Keith C
                                  Aug 6 at 9:01












                                • 1




                                  Suggest you mention the need to avoid the risk of SOQL Injection too.
                                  – Keith C
                                  Aug 6 at 9:01







                                1




                                1




                                Suggest you mention the need to avoid the risk of SOQL Injection too.
                                – Keith C
                                Aug 6 at 9:01




                                Suggest you mention the need to avoid the risk of SOQL Injection too.
                                – Keith C
                                Aug 6 at 9:01










                                up vote
                                -2
                                down vote













                                As per your query it's returning integer value i.e. Count always should be an integer.



                                Integer q1 = 'SELECT count() FROM Case WHERE '+q;


                                It would be great if you are explaining bit more on below code.



                                totalCount = [q1]; - I believe, this is not a correct syntax






                                share|improve this answer

























                                  up vote
                                  -2
                                  down vote













                                  As per your query it's returning integer value i.e. Count always should be an integer.



                                  Integer q1 = 'SELECT count() FROM Case WHERE '+q;


                                  It would be great if you are explaining bit more on below code.



                                  totalCount = [q1]; - I believe, this is not a correct syntax






                                  share|improve this answer























                                    up vote
                                    -2
                                    down vote










                                    up vote
                                    -2
                                    down vote









                                    As per your query it's returning integer value i.e. Count always should be an integer.



                                    Integer q1 = 'SELECT count() FROM Case WHERE '+q;


                                    It would be great if you are explaining bit more on below code.



                                    totalCount = [q1]; - I believe, this is not a correct syntax






                                    share|improve this answer













                                    As per your query it's returning integer value i.e. Count always should be an integer.



                                    Integer q1 = 'SELECT count() FROM Case WHERE '+q;


                                    It would be great if you are explaining bit more on below code.



                                    totalCount = [q1]; - I believe, this is not a correct syntax







                                    share|improve this answer













                                    share|improve this answer



                                    share|improve this answer











                                    answered Aug 6 at 8:50









                                    Prem Anandh

                                    1468




                                    1468






















                                         

                                        draft saved


                                        draft discarded


























                                         


                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function ()
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsalesforce.stackexchange.com%2fquestions%2f227848%2fconvert-string-to-query%23new-answer', 'question_page');

                                        );

                                        Post as a guest













































































                                        Comments

                                        Popular posts from this blog

                                        What does second last employer means? [closed]

                                        List of Gilmore Girls characters

                                        Confectionery