Nested Dynamic SOQL Query2019 Community Moderator ElectionSplit a single field into 2 columns for a VF pageJSON serialize is not handling aggregate results properly in Spring 13Getting error “System.LimitException: Too many query rows: 50001” what i do in this case.Best Approach/Way to Query Single SObject recordNeed help writing test Apex ClasseSearch by '.' causes non-selective query exceptionschema.getglobaldescribe needs test classNot able to escape quote in visualforce page?fault string: No such parameter param defined for the operation, please check the WSDL for the serviceUnable to query with cross-Object pick-list field filter on Custom Metadata SOQL

Why is "la Gestapo" feminine?

Symbolism of 18 Journeyers

UK Tourist Visa- Enquiry

Would mining huge amounts of resources on the Moon change its orbit?

Is VPN a layer 3 concept?

Someone scrambled my calling sign- who am I?

How do researchers send unsolicited emails asking for feedback on their works?

Why do I have a large white artefact on the rendered image?

Writing in a Christian voice

Determine voltage drop over 10G resistors with cheap multimeter

What is the difference between something being completely legal and being completely decriminalized?

How to read string as hex number in bash?

How can an organ that provides biological immortality be unable to regenerate?

Extraneous elements in "Europe countries" list

PTIJ: Which Dr. Seuss books should one obtain?

Norwegian Refugee travel document

What will the Frenchman say?

How do you justify more code being written by following clean code practices?

Why is participating in the European Parliamentary elections used as a threat?

Why is this tree refusing to shed its dead leaves?

Exit shell with shortcut (not typing exit) that closes session properly

Friend wants my recommendation but I don't want to

What (if any) is the reason to buy in small local stores?

Does fire aspect on a sword, destroy mob drops?



Nested Dynamic SOQL Query



2019 Community Moderator ElectionSplit a single field into 2 columns for a VF pageJSON serialize is not handling aggregate results properly in Spring 13Getting error “System.LimitException: Too many query rows: 50001” what i do in this case.Best Approach/Way to Query Single SObject recordNeed help writing test Apex ClasseSearch by '.' causes non-selective query exceptionschema.getglobaldescribe needs test classNot able to escape quote in visualforce page?fault string: No such parameter param defined for the operation, please check the WSDL for the serviceUnable to query with cross-Object pick-list field filter on Custom Metadata SOQL










3















I am Trying to write a dynamic SOQL Query with a nested query.



@AuraEnabled
public static List<Books__c> filterRecords(String bookNumber, String PDCN, String Brand, String Type)
System.debug('bookNumber__c->'+bookNumber__c);
System.debug('PDCN->'+PDCN);
System.debug('Brand->'+Brand);

String query = 'SELECT Id,Content__c,ForecastWeekIndicator__c,Generic_PDCN__c,isExpired__c, '+
'BrandStandardName__c,DPForecast_BaseUnits__c,ForecastStatus__c,Generic_DateTime__c, '+
'Type__c,OperationalForecast_BaseUnits__c,PackageStandardName__c,bookNumber__c__c '+
'FROM Books__c WHERE Type__c =:Type '+
'AND Id NOT IN (SELECT Books__c FROM User_Specific_Books__c '+
'WHERE Books_Delete__c = TRUE AND User__c = : UserInfo.getUserId())';
if(string.isNotEmpty(bookNumber__c) && bookNumber__c!=null)
query = query + ' AND bookNumber__c__c =: bookNumber__c';

if(string.isNotEmpty(PDCN) && PDCN != null)
query = query + ' AND Generic_PDCN__c =: PDCN';

if(string.isNotEmpty(Brand) && Brand != null)
query = query + ' AND BrandStandardName__c =: Brand';

System.debug('query--->'+query);
List<Notification__c> lst;

try
lst = Database.query(query);
system.debug('List--->'+lst);

catch(Exception e)
system.debug(e.getMessage());


if(!lst.isEmpty())
return lst;

else
return null;

}


and, I am getting exception expecting a right parentheses, found '('.
Any explanation would be appreciated.










share|improve this question




























    3















    I am Trying to write a dynamic SOQL Query with a nested query.



    @AuraEnabled
    public static List<Books__c> filterRecords(String bookNumber, String PDCN, String Brand, String Type)
    System.debug('bookNumber__c->'+bookNumber__c);
    System.debug('PDCN->'+PDCN);
    System.debug('Brand->'+Brand);

    String query = 'SELECT Id,Content__c,ForecastWeekIndicator__c,Generic_PDCN__c,isExpired__c, '+
    'BrandStandardName__c,DPForecast_BaseUnits__c,ForecastStatus__c,Generic_DateTime__c, '+
    'Type__c,OperationalForecast_BaseUnits__c,PackageStandardName__c,bookNumber__c__c '+
    'FROM Books__c WHERE Type__c =:Type '+
    'AND Id NOT IN (SELECT Books__c FROM User_Specific_Books__c '+
    'WHERE Books_Delete__c = TRUE AND User__c = : UserInfo.getUserId())';
    if(string.isNotEmpty(bookNumber__c) && bookNumber__c!=null)
    query = query + ' AND bookNumber__c__c =: bookNumber__c';

    if(string.isNotEmpty(PDCN) && PDCN != null)
    query = query + ' AND Generic_PDCN__c =: PDCN';

    if(string.isNotEmpty(Brand) && Brand != null)
    query = query + ' AND BrandStandardName__c =: Brand';

    System.debug('query--->'+query);
    List<Notification__c> lst;

    try
    lst = Database.query(query);
    system.debug('List--->'+lst);

    catch(Exception e)
    system.debug(e.getMessage());


    if(!lst.isEmpty())
    return lst;

    else
    return null;

    }


    and, I am getting exception expecting a right parentheses, found '('.
    Any explanation would be appreciated.










    share|improve this question


























      3












      3








      3








      I am Trying to write a dynamic SOQL Query with a nested query.



      @AuraEnabled
      public static List<Books__c> filterRecords(String bookNumber, String PDCN, String Brand, String Type)
      System.debug('bookNumber__c->'+bookNumber__c);
      System.debug('PDCN->'+PDCN);
      System.debug('Brand->'+Brand);

      String query = 'SELECT Id,Content__c,ForecastWeekIndicator__c,Generic_PDCN__c,isExpired__c, '+
      'BrandStandardName__c,DPForecast_BaseUnits__c,ForecastStatus__c,Generic_DateTime__c, '+
      'Type__c,OperationalForecast_BaseUnits__c,PackageStandardName__c,bookNumber__c__c '+
      'FROM Books__c WHERE Type__c =:Type '+
      'AND Id NOT IN (SELECT Books__c FROM User_Specific_Books__c '+
      'WHERE Books_Delete__c = TRUE AND User__c = : UserInfo.getUserId())';
      if(string.isNotEmpty(bookNumber__c) && bookNumber__c!=null)
      query = query + ' AND bookNumber__c__c =: bookNumber__c';

      if(string.isNotEmpty(PDCN) && PDCN != null)
      query = query + ' AND Generic_PDCN__c =: PDCN';

      if(string.isNotEmpty(Brand) && Brand != null)
      query = query + ' AND BrandStandardName__c =: Brand';

      System.debug('query--->'+query);
      List<Notification__c> lst;

      try
      lst = Database.query(query);
      system.debug('List--->'+lst);

      catch(Exception e)
      system.debug(e.getMessage());


      if(!lst.isEmpty())
      return lst;

      else
      return null;

      }


      and, I am getting exception expecting a right parentheses, found '('.
      Any explanation would be appreciated.










      share|improve this question
















      I am Trying to write a dynamic SOQL Query with a nested query.



      @AuraEnabled
      public static List<Books__c> filterRecords(String bookNumber, String PDCN, String Brand, String Type)
      System.debug('bookNumber__c->'+bookNumber__c);
      System.debug('PDCN->'+PDCN);
      System.debug('Brand->'+Brand);

      String query = 'SELECT Id,Content__c,ForecastWeekIndicator__c,Generic_PDCN__c,isExpired__c, '+
      'BrandStandardName__c,DPForecast_BaseUnits__c,ForecastStatus__c,Generic_DateTime__c, '+
      'Type__c,OperationalForecast_BaseUnits__c,PackageStandardName__c,bookNumber__c__c '+
      'FROM Books__c WHERE Type__c =:Type '+
      'AND Id NOT IN (SELECT Books__c FROM User_Specific_Books__c '+
      'WHERE Books_Delete__c = TRUE AND User__c = : UserInfo.getUserId())';
      if(string.isNotEmpty(bookNumber__c) && bookNumber__c!=null)
      query = query + ' AND bookNumber__c__c =: bookNumber__c';

      if(string.isNotEmpty(PDCN) && PDCN != null)
      query = query + ' AND Generic_PDCN__c =: PDCN';

      if(string.isNotEmpty(Brand) && Brand != null)
      query = query + ' AND BrandStandardName__c =: Brand';

      System.debug('query--->'+query);
      List<Notification__c> lst;

      try
      lst = Database.query(query);
      system.debug('List--->'+lst);

      catch(Exception e)
      system.debug(e.getMessage());


      if(!lst.isEmpty())
      return lst;

      else
      return null;

      }


      and, I am getting exception expecting a right parentheses, found '('.
      Any explanation would be appreciated.







      apex soql






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 8 hours ago









      Mark Pond

      18.5k13288




      18.5k13288










      asked 10 hours ago









      Thomas PeteThomas Pete

      457




      457




















          2 Answers
          2






          active

          oldest

          votes


















          6














          You can't use actual Apex in dynamic queries. Only "simple" variables are allowed. The problem is in the following line.



           'WHERE Books_Delete__c = TRUE AND User__c = : UserInfo.getUserId())';


          Assign the value to a variable first:



          Id userId = UserInfo.getUserId();
          ...
          'WHERE Books_Delete__c = TRUE AND User__c = :userId)';





          share|improve this answer























          • Worked! Thanks.

            – Thomas Pete
            10 hours ago











          • @ThomasPete you're welcome! P.S. String.isNotBlank also checks for null values, no need to check that separately in your code.

            – sfdcfox
            9 hours ago


















          5














          You can't use dot reference in dynamic query. Here is your problem:



          'WHERE Books_Delete__c = TRUE AND User__c = : UserInfo.getUserId())'


          You need to add some context variable to store the Id and then change it to:



          'WHERE Books_Delete__c = TRUE AND User__c = :runningUserId'





          share|improve this answer























          • Thanks, Adding a context variable did it!

            – Thomas Pete
            9 hours ago










          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',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          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%2f254321%2fnested-dynamic-soql-query%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          6














          You can't use actual Apex in dynamic queries. Only "simple" variables are allowed. The problem is in the following line.



           'WHERE Books_Delete__c = TRUE AND User__c = : UserInfo.getUserId())';


          Assign the value to a variable first:



          Id userId = UserInfo.getUserId();
          ...
          'WHERE Books_Delete__c = TRUE AND User__c = :userId)';





          share|improve this answer























          • Worked! Thanks.

            – Thomas Pete
            10 hours ago











          • @ThomasPete you're welcome! P.S. String.isNotBlank also checks for null values, no need to check that separately in your code.

            – sfdcfox
            9 hours ago















          6














          You can't use actual Apex in dynamic queries. Only "simple" variables are allowed. The problem is in the following line.



           'WHERE Books_Delete__c = TRUE AND User__c = : UserInfo.getUserId())';


          Assign the value to a variable first:



          Id userId = UserInfo.getUserId();
          ...
          'WHERE Books_Delete__c = TRUE AND User__c = :userId)';





          share|improve this answer























          • Worked! Thanks.

            – Thomas Pete
            10 hours ago











          • @ThomasPete you're welcome! P.S. String.isNotBlank also checks for null values, no need to check that separately in your code.

            – sfdcfox
            9 hours ago













          6












          6








          6







          You can't use actual Apex in dynamic queries. Only "simple" variables are allowed. The problem is in the following line.



           'WHERE Books_Delete__c = TRUE AND User__c = : UserInfo.getUserId())';


          Assign the value to a variable first:



          Id userId = UserInfo.getUserId();
          ...
          'WHERE Books_Delete__c = TRUE AND User__c = :userId)';





          share|improve this answer













          You can't use actual Apex in dynamic queries. Only "simple" variables are allowed. The problem is in the following line.



           'WHERE Books_Delete__c = TRUE AND User__c = : UserInfo.getUserId())';


          Assign the value to a variable first:



          Id userId = UserInfo.getUserId();
          ...
          'WHERE Books_Delete__c = TRUE AND User__c = :userId)';






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered 10 hours ago









          sfdcfoxsfdcfox

          259k12205449




          259k12205449












          • Worked! Thanks.

            – Thomas Pete
            10 hours ago











          • @ThomasPete you're welcome! P.S. String.isNotBlank also checks for null values, no need to check that separately in your code.

            – sfdcfox
            9 hours ago

















          • Worked! Thanks.

            – Thomas Pete
            10 hours ago











          • @ThomasPete you're welcome! P.S. String.isNotBlank also checks for null values, no need to check that separately in your code.

            – sfdcfox
            9 hours ago
















          Worked! Thanks.

          – Thomas Pete
          10 hours ago





          Worked! Thanks.

          – Thomas Pete
          10 hours ago













          @ThomasPete you're welcome! P.S. String.isNotBlank also checks for null values, no need to check that separately in your code.

          – sfdcfox
          9 hours ago





          @ThomasPete you're welcome! P.S. String.isNotBlank also checks for null values, no need to check that separately in your code.

          – sfdcfox
          9 hours ago













          5














          You can't use dot reference in dynamic query. Here is your problem:



          'WHERE Books_Delete__c = TRUE AND User__c = : UserInfo.getUserId())'


          You need to add some context variable to store the Id and then change it to:



          'WHERE Books_Delete__c = TRUE AND User__c = :runningUserId'





          share|improve this answer























          • Thanks, Adding a context variable did it!

            – Thomas Pete
            9 hours ago















          5














          You can't use dot reference in dynamic query. Here is your problem:



          'WHERE Books_Delete__c = TRUE AND User__c = : UserInfo.getUserId())'


          You need to add some context variable to store the Id and then change it to:



          'WHERE Books_Delete__c = TRUE AND User__c = :runningUserId'





          share|improve this answer























          • Thanks, Adding a context variable did it!

            – Thomas Pete
            9 hours ago













          5












          5








          5







          You can't use dot reference in dynamic query. Here is your problem:



          'WHERE Books_Delete__c = TRUE AND User__c = : UserInfo.getUserId())'


          You need to add some context variable to store the Id and then change it to:



          'WHERE Books_Delete__c = TRUE AND User__c = :runningUserId'





          share|improve this answer













          You can't use dot reference in dynamic query. Here is your problem:



          'WHERE Books_Delete__c = TRUE AND User__c = : UserInfo.getUserId())'


          You need to add some context variable to store the Id and then change it to:



          'WHERE Books_Delete__c = TRUE AND User__c = :runningUserId'






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered 10 hours ago









          Adrian LarsonAdrian Larson

          109k19115247




          109k19115247












          • Thanks, Adding a context variable did it!

            – Thomas Pete
            9 hours ago

















          • Thanks, Adding a context variable did it!

            – Thomas Pete
            9 hours ago
















          Thanks, Adding a context variable did it!

          – Thomas Pete
          9 hours ago





          Thanks, Adding a context variable did it!

          – Thomas Pete
          9 hours ago

















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Salesforce Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsalesforce.stackexchange.com%2fquestions%2f254321%2fnested-dynamic-soql-query%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          How to create a command for the “strange m” symbol in latex? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)How do you make your own symbol when Detexify fails?Writing bold small caps with mathpazo packageplus-minus symbol with parenthesis around the minus signGreek character in Beamer document titleHow to create dashed right arrow over symbol?Currency symbol: Turkish LiraDouble prec as a single symbol?Plus Sign Too Big; How to Call adfbullet?Is there a TeX macro for three-legged pi?How do I get my integral-like symbol to align like the integral?How to selectively substitute a letter with another symbol representing the same letterHow do I generate a less than symbol and vertical bar that are the same height?

          Българска екзархия Съдържание История | Български екзарси | Вижте също | Външни препратки | Литература | Бележки | НавигацияУстав за управлението на българската екзархия. Цариград, 1870Слово на Ловешкия митрополит Иларион при откриването на Българския народен събор в Цариград на 23. II. 1870 г.Българската правда и гръцката кривда. От С. М. (= Софийски Мелетий). Цариград, 1872Предстоятели на Българската екзархияПодмененият ВеликденИнформационна агенция „Фокус“Димитър Ризов. Българите в техните исторически, етнографически и политически граници (Атлас съдържащ 40 карти). Berlin, Königliche Hoflithographie, Hof-Buch- und -Steindruckerei Wilhelm Greve, 1917Report of the International Commission to Inquire into the Causes and Conduct of the Balkan Wars

          Чепеларе Съдържание География | История | Население | Спортни и природни забележителности | Културни и исторически обекти | Религии | Обществени институции | Известни личности | Редовни събития | Галерия | Източници | Литература | Външни препратки | Навигация41°43′23.99″ с. ш. 24°41′09.99″ и. д. / 41.723333° с. ш. 24.686111° и. д.*ЧепелареЧепеларски Linux fest 2002Начало на Зимен сезон 2005/06Национални хайдушки празници „Капитан Петко Войвода“Град ЧепелареЧепеларе – народният ски курортbgrod.orgwww.terranatura.hit.bgСправка за населението на гр. Исперих, общ. Исперих, обл. РазградМузей на родопския карстМузей на спорта и скитеЧепеларебългарскибългарскианглийскитукИстория на градаСки писти в ЧепелареВремето в ЧепелареРадио и телевизия в ЧепелареЧепеларе мами с родопски чар и добри пистиЕвтин туризъм и снежни атракции в ЧепелареМестоположениеИнформация и снимки от музея на родопския карст3D панорами от ЧепелареЧепелареррр