Search code examples
sqlplsqlformattingora-00933to-char

ORA-00933 Error for to_char formatting PLSQL


I have the following codes:

IF nvl(p_value, 0) >= 0 THEN
      l_currency_prefix := 'scc.currency_prefix_pos';
      l_currency_suffix := 'scc.currency_suffix_pos';
    ELSE
      l_currency_prefix := 'scc.currency_prefix_neg';
      l_currency_suffix := 'scc.currency_suffix_neg';
    END IF;

l_query := 'SELECT nvl('||l_currency_prefix||', '')'
                       ||'trim(to_char('||p_value||
                                       ',scc.currency_format
                                        ,'||'NLS_NUMERIC_CHARACTERS=' || 'scc.decimal_group_separator'||'))'
                       ||'nvl('||l_currency_suffix||',  '')
              FROM gss.gss_currency_locale scc
             WHERE scc.country_code =' ||p_country_code||
              'AND scc.currency_code ='|| p_currency_code||
              'AND rownum=1';

and here is the dbms output for l_query:

SELECT nvl(scc.currency_prefix_pos, ')trim(to_char(10000,scc.currency_format
                                            ,NLS_NUMERIC_CHARACTERS=scc.decimal_group_separator))nvl(scc.currency_suffix_pos, ')
                  FROM gss.gss_currency_locale scc
                 WHERE scc.country_code =USAND scc.currency_code =USDAND rownum=1

However, it keep showing an ORA-00933 errors. I debug these piece of code for few hours and could not find where is the errors. Could some one please provide some advice on this?


Solution

  • Now some of the problems are obvious. You need something like this:

    l_query := 'SELECT nvl('||l_currency_prefix||',
                           ||'trim(to_char('||p_value||
                                           ',scc.currency_format || ')' ||
                  FROM gss.gss_currency_locale scc
                 WHERE scc.country_code = ''' ||p_country_code|| '''' ||
                  ' AND scc.currency_code = '''|| p_currency_code|| '''' ||
                  ' AND rownum=1';
    

    (I'm not sure if that is 100 percent correct.)

    Usually, when creating queries this way, I use replace() instead of direct substitution. Something like:

    l_query := 'select nvl(@currency_prefix, trim(@p_value, @currency_format))
    from . . . ';
    l_query := replace(l_query, '@currency_prefix', l_currency_prefix);
    l_query := replace(l_query, '@p_value', p_value);
    . . .
    

    I find that this approach makes it much easier to maintain the code and to see what it is doing.