JSF inputText takes apostrophe (single quote) as end of string

Hi,
I run into a problem with JSF when apostrophe(single quote) is in input text:
<h:inputText id="input1" styleClass="field" size="20" maxlength="20" value="#{bean.property1}" />
When user inputs string contains apostrophe (single quote), for example "John's task", the bean only gets "John". The text after the apostrophy is gone. It seems that the inputText takes apostrohe as end of the string.
I also test with escaple sequence, for example, input is "John\' task", the result in bean is still "John"
input is "John\\\' task", the result in bean is "John
It doesn't have problem with other special characters, such as "<">", "@" , double quote etc.
Finally, I fix the problem by replacing apostrohy with "& # 0 3 9".
I just wonder if anyone has similar prolbem and wehether this is some bug in certain version of JSTL or some configuration issue ( for example, some definittion for end of the string in some config file, etc).
Your insight is appreciated.
Thanks

Without the actual code we can't be of any meaning for you. Create a small reprocudeable test case and post the actual code here. For example:
JSF<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<f:view>
    <html>
        <head>
            <title>test</title>
        </head>
        <body>
            <h:form>
                <h:inputText value="#{myBean.value}" />
                <h:commandButton value="submit" action="#{myBean.action}" />
                <h:outputText value="#{myBean.value}" />
            </h:form>
        </body>
    </html>
</f:view>MyBeanpackage mypackage;
public class MyBean {
    private String value;
    public void action() {
        System.out.println(value);
    public String getValue() {
        return value;
    public void setValue(String value) {
        this.value = value;
}faces-config:<faces-config>
    <managed-bean>
        <managed-bean-name>myBean</managed-bean-name>
        <managed-bean-class>mypackage.MyBean</managed-bean-class>
        <managed-bean-scope>request</managed-bean-scope>
    </managed-bean>
</faces-config>Which works fine by the way.

Similar Messages

  • Jstl inputText takes apostrophe (single quote) as end of string

    Hi,
    I run into a problem with jstl when apostrophe(single quote) is in input text:
    <h:inputText id="input1" styleClass="field" size="20" maxlength="20" value="#{bean.property1}" />
    When user inputs string contains apostrophe (single quote), for example "John's task", the bean only gets "John". The text after the apostrophy is gone. It seems that the inputText takes apostrohe as end of the string.
    I also test with escaple sequence, for example, input is "John\' task", the result in bean is still "John"
    input is "John\\\' task", the result in bean is "John\\".
    It doesn't have problem with other special characters, such as "<".">",""", "@" etc.
    Finally, I fix the problem by replacing apostrohy with "&#039;".
    I just wonder if anyone has similar prolbem and wehether this is some bug in certain version of JSTL or some configuration issue ( for example, some definittion for end of the string in some config file, etc).I'm using JSTL 1.1.1.2.
    Your insight is appreciated.
    Thanks

    This isn't JSTL, it's JSF. There's a separate forum for this: http://forum.java.sun.com/forum.jspa?forumID=427
    I think the escape character for a single quote is the single quote itself. Give that a shot.
    People on the forum help others voluntarily, it's not their job.
    Help them help you.
    Learn how to ask questions first: http://faq.javaranch.com/java/HowToAskQuestionsOnJavaRanch
    (Yes I know it's on JavaRanch but I think it applies everywhere)
    ----------------------------------------------------------------

  • Query with Apostrophe (single quote)

    Hi all,
    I have noticed that when you enter a search string with an apostrophe (eg. Tito's Station) in a textbox on a form linked to a table and hit the Query button, it generates an sql error. I think this is cos u cannot have an apostrophe (single quote) in the search string in a "where" clause.
    I am using Portal version 3.0.6.6.5 on an 8.1.7 database.
    I have logged a tar (1744105.999) for this but it is said to be a bug (1759202). I wish to enquire whether any of you have had this problem with a later version or at which version leve this bug has been fixed.
    Does any1 know how to limit the text typed into a texbox, so that it wont accept certain characters (eg. the apostrophe key) ??
    Thanks

    Hi Rene'
    Thanks for your help! This will definitely help me alot! I am a little baffled with your code for delimiting the single quote. I tried it and it doesnt work.
    Thanks very much for the response
    Naseem
    <BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by Rene' Castle ([email protected]):
    This is still an issue in 3.0.8.9.8. You can use a Javascript validation routine to disallow special characters.
    If you want to check to see that they only enter certain things you can do:
    var s = theElement.value;
    var filter=/^[a-zA-Z]{1,}$/;
    if (s.length == 0 ) return true;
    if (filter.test(s))
    return true;
    else
    alert(" Please input a valid character" );
    theElement.focus();
    theElement.select();
    return false;
    The above code would only allow one or more alphabetic characters. You could make it [a-zA-Z0-9] to allow alphanumeric characters. You could also allow anything but specific characters by doing the following:
    var s = theElement.value;
    var filter=/[^']*/;
    if (s.length == 0 ) return true;
    if (filter.test(s))
    alert(" Please input a string without a single quote (') in it" );
    theElement.focus();
    theElement.select();
    return false;
    else
    return true;
    Hope this gets you started.
    Rene'<HR></BLOCKQUOTE>
    null

  • Apostrophes (single quote) are lost when generating DDL code.

    Hi,
    ODI Version : 11.1.1.5.0
    Java version : 1.6.0_24
    Database version : Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit Production
    Context: Generating DDL code for a an ODI Model
    PROBLEMATIC: When generating DDL code, all apostrophes (single quote: ') are removed from Datastore Descriptions and Datastore Colunms Descriptions in the process of generating Comments on Tables and Comments on Tables Columns. I tried to double, even triple apostrophes (in descriptions), without success. I also tried double quotes (") without success either.
    Ex: Datastore Column Description: *+ID de l'utilisateur+* becomes *+comment on table ... is 'ID de l utilisateur'+* in generated procedure.
    Do you know a way to keep the apostrophes when creating Comments on Columns and Oracle Tables by generating DDL code ?
    Regards,
    Gaston
    Edited by: uleblga on 23-May-2012 3:42 PM
    Edited by: uleblga on 23-May-2012 3:42 PM

    Nobody has a clue as how to handle this problem ?
    Regards,
    Gaston

  • Copying a table with the right-click menu in schema browser fails to copy comments when string has single quote(s) (ascii chr(39))

    Hi,
    I'm running 32-bit version of SQL Developer v. 3.2.20.09 build 09.87, and I used the built in context menu (right-clicking from the schema browser) today to copy a table.  However, none of the comments copied.  When I dug into the PL/SQL that the menu-item is using, I realized that it fails because it doesn't handle single quotes within the comment string.
    For example, I have a table named WE_ENROLL_SNAPSHOT that I wanted to copy as WE_ENROLL_SNAPSHOT_V1 (within same schema name)
    1. I right-clicked on the object in the schema browser and selected Table > Copy...
    2. In the pop-up Copy window, I entered the new table name "WE_ENROLL_SNAPSHOT_V1" and ticked the box for "Include Data" option.  -- The PL/SQL that the menu-command is using is in the "SQL" tab of this window.  This is what I extracted later for testing the issue after the comments did not copy.
    Result: Table and data copied as-expected, but no column or table comments existed.
    I examined the PL/SQL block that the pop-up window issued, and saw this:
    declare
      l_sql varchar2(32767);
      c_tab_comment varchar2(32767);
      procedure run(p_sql varchar2) as
      begin
         execute immediate p_sql;
      end;
    begin
    run('create table "BI_ETL".WE_ENROLL_SNAPSHOT_V1 as select * from "BI_ETL"."WE_ENROLL_SNAPSHOT" where '||11||' = 11');
    select comments into c_tab_comment from sys.all_TAB_comments where owner = 'BI_ETL' and table_name = 'WE_ENROLL_SNAPSHOT' and comments is not null;
    run('comment on table BI_ETL.WE_ENROLL_SNAPSHOT_V1 is '||''''||c_tab_comment||'''');
    for tc in (select column_name from sys.all_tab_cols where owner = 'BI_ETL' and table_name = 'WE_ENROLL_SNAPSHOT')
        loop
       for c in (select comments from sys.all_col_comments where owner = 'BI_ETL' and table_name = 'WE_ENROLL_SNAPSHOT' and column_name=tc.column_name)
       loop
       run ('comment on column BI_ETL.WE_ENROLL_SNAPSHOT_V1.'||tc.column_name||' is '||''''||c.comments||'''');
    end loop;
    end loop;
    EXCEPTION
      WHEN OTHERS THEN NULL;
    end;
    The string of the table comment on WE_ENROLL_SNAPSHOT is this:
    WBIG table of frozen, point-in-time snapshots of Enrolled Students by Category/term/pidm. "Category" is historically, and commonly, our CENSUS snapshot; but, can also describe other frequencies, or categorizations, such as: End-of-Term (EOT), etc. Note: Prior to this table existing, Census-snapshots were stored in SATURN.SNAPREG_ALL. All FALL and SPRING term records prior-to-and-including Spring 2013 ('201230') have been migrated into this table -- EXCEPT a few select prior to Fall 2004 (200410) records where there are duplicates on term/pidm. NO Summer snapshots existed in SNAPREG_ALL, but were queried and stored retroactively (including terms prior to Spring 2013) for the purpose of future on-going year-over-year analysis and comparison.
    Note the single quotes in the comment: ... ('201230')
    So, in the above PL/SQL line 11 grabs this string into "c_tab_comment", but then line 12 fails because of the single quotes.  It doesn't know how to end the string because the single quotes in the string are not "escaped", and this messes up the concatenation on line 12.  (So, then no other column comments are created either because the block throws an error, and goes to line 22 for the exception and exits.)
    When I modify the above PL/SQL as my own anonymous block like this, it is successful:
    declare
      c_tab_comment VARCHAR2(32767);
    begin
    SELECT REPLACE(comments,chr(39),chr(39)||chr(39)) INTO c_tab_comment FROM sys.all_TAB_comments WHERE owner = 'BI_ETL'   AND table_name = 'WE_ENROLL_SNAPSHOT'  AND comments IS NOT NULL;
    EXECUTE IMMEDIATE 'comment on table BI_ETL.WE_ENROLL_SNAPSHOT_V1 is '''||c_tab_comment||'''';
    for tc in (select column_name from sys.all_tab_cols where owner = 'BI_ETL' and table_name = 'WE_ENROLL_SNAPSHOT')
        loop
       for c in (select REPLACE(comments,chr(39),chr(39)||chr(39)) comments from sys.all_col_comments where owner = 'BI_ETL' and table_name = 'WE_ENROLL_SNAPSHOT' and column_name=tc.column_name)
       loop
       EXECUTE IMMEDIATE 'comment on column BI_ETL.WE_ENROLL_SNAPSHOT_V1.'||tc.column_name||' is '||''''||c.comments||'''';
    end loop;
    end loop;
    EXCEPTION
      WHEN OTHERS THEN NULL;
    end;
    On lines 4 and 8 I wrapped the "comments" from sys.all_tab_comments and sys.all_col_comments with a replace command finding every chr(39) and replacing with chr(39)||chr(39). (On line 8 I also had to alias the wrapped column as "comments" so line 10 would succeed.)
    Is this an issue with SQL Developer? Is there any chance that the menu-items can handle single quotes in comment strings? ... And, of course this makes me wonder which other context menu commands in the tool might have a similar issue.
    Thoughts?
    thanks//jacob

    PaigeT wrote:
    I know about quick drop, but it isn't helpful here. I want to be able to right click on a string or array wire, navigate to the string or array palette, and select the corresponding "Empty?" comparator. In this case, since I do actually know where those functions live, and I'm already using my mouse to right click on the wire, typing ctrl-space to open quick drop and then typing in the function name is actually more work than navigating to it in the palette. It would just be nice to have it on hand in the location I naturally go to look for it the first time. 
    I don't agree with this work flow.  Right hand on mouse, left hand on home keys.  Pressing CTRL + Space is done with the left hands, and then you could assign "ea" to "Empty Array" both of which is accessible with the left hand.  Darren posted a bunch of great shortcuts for the right handed developer.
    https://decibel.ni.com/content/docs/DOC-20453
    This is much faster than waiting for any right click menu navigation, even if it is found in the suggested subpalette.
    Unofficial Forum Rules and Guidelines - Hooovahh - LabVIEW Overlord
    If 10 out of 10 experts in any field say something is bad, you should probably take their opinion seriously.

  • Column Template conditions foiled by a single quote

    I am using a generic column template and have a few pl/sql conditions to shade different rows like so:
    '#1'  like '%Total%'This worked fine until an employee's name appeared in the first column with a single quote in his last name (like O'Brien). Well apparently Apex literally takes whatever is in the field and just shoves it in between the single quotes because the single quote is terminating the string as if you were doing this in sql instead of making it a bind variable:
    'O'BRIEN' like '%Total%'Which results in this friendly message to the users:
    ORA-06550: line 1, column 65: PLS-00103: Encountered the symbol "BRIEN" when expecting one of the following: ) , * & | = - + < / > at in is mod remainder not rem => ..  <> or != or ~= >= <= <> and or like LIKE2_ LIKE4_ LIKEC_ as between from using || multiset member SUBMULTISET_
         Error      ERR-1025 Error processing PLSQL expression. 'O'BRIEN, JOHN P ' like '%Total%' Can someone from the Apex team confirm that this is the issue? I know I could do a replace on the single quote in my sql, but can't figure out how to escape the '#1#' properly so I don't have to do a replace. I also don't really want to use the Carl Backstrom approach of having to code in a class into the sql when these templates work for 99% of what I need to do.
    Any ideas?

    Dude you rock! I tried about 6 different combos of the q function before I got frustrated and posted. I had too many quotes in mine I guess but that works perfectly.
    Thanks again!

  • Adding a single quote

    Hi
    I am trying to check through a String before it is sent to the database to add in an extra single quote if a single quote is in the String, but it's not working
    char singleQuote = '\'';
    private static String prepareString (String SQLQuery) {
    StringBuffer sb = new StringBuffer();
    for(int j =0; j<SQLQuery.length(); j++) {
    char c = SQLQuery.charAt(j);
    //problems here
    if(c.equals(singleQuote)){
    sb.insert((j+1), "\'")
    return sb.toString();I am getting some message about not being able to "dereference" c, but don't know what it means, nor if I am doing this right.
    Anyone know how to take care of this? Also, any other common error checks that should be made before sending a query to a db?
    Thanks!

    Try replacing the line...
    if(c.equals(singleQuote)){with the line...
    if(c == singleQuote){

  • Is it possible to use single quotes in a String

    Can we use single quotes and comma in side a string variable...
    Eg: String s=" a ' , ' b ";
    why am i asking was...... when this variable is sent to database, the table automatically recognizes the beginning single quotes and end single quotes to retreive the value from the table....
    Eg for query:
    select code from gm_code where sub_code in(?);
    when we pass those two value to this query.. it have to execute like the following
    select code from gm_code where sub_code in(' a ' , ' b');
    but it is not executing.....
    can you give me some suggestion to resolve this problem..
    Thanks in advance..

    You need two strings, and you don't need to provide the single quotes. The driver does that for you when you use PreparedStatment's parameters.
    ps = con.prepareStatement("select * from foo where bar in (?, ?)");
    ps.setString(1, "a");
    ps.setString(2, "b");
    rs = ps.executeQuery();The actual SQL that's executed is select * from foo where bar in ('a', 'b')

  • Quick key shortcut to apply single quotes?

    Hi All, Do you know if there is a quick key or way inside of MSFT SQL Server MGMT Studio, Query writer to apply single quotes to a large string of text?
    4026, 4081,
    4084, 4091,
    4095, 4101,
    4102, 4106,
    4107, 4112,
    4117, 4121,
    4123, 4124,
    4126, 4135,
    4136, 4137,
    4138, 4140,
    4141, 4146,
    4150, 4152,
    4154, 4201,
    4203, 4208,
    4209, 4210,
    4211, 4217,
    4218, 4224,
    4228, 4230,
    4239, 4241,
    4242, 4248,
    4304, 4306,
    4308, 4322
    to
    '4026', '4081',
    4'084', '4091',
    '4095', '4101',
    '4102' ... etc.
    Thanks,
    :) john

    You can use the fnSplit function (Table-valued function) for tasks involving lists separated with comma or any character separated lists;
    Declare @vSTR varchar(1000)
    Set @vStr = '4026, 4081, 4084, 4091, 4095, 4101, 4102, 4106, 4107, 4112, 4117, 4121, 4123, 4124, 4126, 4135, 4136, 4137, 4138, 4140, 4141, 4146, 4150, 4152, 4154, 4201, 4203, 4208, 4209, 4210, 4211, 4217, 4218, 4224, 4228, 4230, 4239, 4241, 4242, 4248, 4304, 4306, 4308, 4322'
    Select '''' + Value + '''' from dbo.fnSplit(@vSTR,',')
    If you don have fnSplit, here is the code. This is a very useful function and can be used for future as well.
    /****** Object: UserDefinedFunction [dbo].[fnSplit] Script Date: 8/11/2014 10:03:31 AM ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    ALTER function [dbo].[fnSplit]
    (@pString nvarchar(max),@pSplitChar char(1))
    returns @tblTemp table (tid int,value varchar(1000))
    as
    begin
    declare @vStartPosition int
    declare @vSplitPosition int
    declare @vSplitValue varchar(1000)
    declare @vCounter int
    set @vCounter=1
    select @vStartPosition = 1,@vSplitPosition=0
    set @vSplitPosition = charindex( @pSplitChar , @pString , @vStartPosition )
    if (@vSplitPosition=0 and len(@pString) != 0)
    begin
    INSERT INTO @tblTemp
    tid ,
    value
    VALUES
    1 ,
    @pString
    return --------------------------------------------------------------->>
    end
    set @pString=@pString+@pSplitChar
    while (@vSplitPosition > 0 )
    begin
    set @vSplitValue = substring( @pString , @vStartPosition , @vSplitPosition - @vStartPosition )
    set @vSplitValue = ltrim(rtrim(@vSplitValue))
    INSERT INTO @tblTemp
    tid ,
    value
    VALUES
    @vCounter ,
    @vSplitValue
    set @vCounter=@vCounter+1
    set @vStartPosition = @vSplitPosition + 1
    set @vSplitPosition = charindex( @pSplitChar , @pString , @vStartPosition )
    end
    return
    end
    Please visit my Blog for some easy and often used t-sql scripts
    My BizCard

  • String with embedded single quote

    Hi, all. We're trying to pass a string from one procedure to another, which will then do an EXECUTE IMMEDIATE on it. However, there are single quotes withing the string, and they're driving us nuts! This is what the concatenated string should look like when passed to the pw_execDDL procedure:
    insert into appimmunization.wsrprfs (inoc_id, proof, is_valid,proof_num) values ('MEAG', to_date('02-OCT-05','DD-MMM-YY'), 'Y',1);
    Here's the concatenation process that doesn't work, and there are functions being called within the string:
    chr_sql := 'insert into appimmunization.wsrprfs (inoc_id, proof, is_valid,proof_num) values (' || '''' || prm_inoc_id || '''' || ', ' || 'to_date(' || '''' || prm_proof1 || ''''||','||'''' ||'DD-MMM-YY'||''''||')' || ', ' || '''' || fw_is_proof_valid(prm_birth_date, prm_proof1) || '''' || ',1);';
    pw_execDDL(chr_sql); /* call the procedure to do the EXECUTE IMMEDIATE */
    Help! We've tried every combination -- using two single quotes together, three, and four, and still no luck. Thanks.

    insert into appimmunization.wsrprfs (inoc_id, proof,
    is_valid,proof_num) values ('MEAG',
    to_date('02-OCT-05','DD-MMM-YY'), 'Y',1);
    This statement can be made in a string with the following affectation:
    chr_sql := 'insert into appimmunization.wsrprfs (inoc_id, proof, is_valid,proof_num) values (''MEAG'', to_date(''02-OCT-05'',''DD-MMM-YY''), ''Y'',1)';
    Note please that each single quote in your original string must be specified using two single quotes and that is all. It is more readable and more easy to do it this way.
    Michel.

  • Update with a Single Quote value

    how do i update a field containing a sigle quote in a record ?
    e.g :
    i have a table s_order_item_xa
    filed: attr_name
    old value: Noofndk
    new value: Noofn's
    how can i update above field value? i am using row_id in where condition to identify rows which i want to update.

    Hi,
    Is the question "How can I include a single-quote character in a string literal?", then the answer is to use 2 of them, like this:
    UPDATE  books
    SET     dewey_num = '291''.4'
    WHERE   dewey_num = '291.4'
    ;In Oracle 10 (and up) you can also use Q-notation. For example:
    UPDATE  books
    SET     dewey_num = Q'[291'.4]'
    WHERE   dewey_num = '291.4'
    ;Edited by: Frank Kulash on Sep 14, 2009 9:51 AM

  • Mssql single quote problem!

    Hi,
    I user servlet to update MS SQL2000. My problem is there is a single quote inside a text string!
    I can't use double quote for string, as it is not a valid statement for MSSQL. I need to use single quote, but there is single quote inside the string, how can I handle the string?
    String mstrnig="I'm a boy";
    String mSQL = "UPDATE news SET " + "title='" + mstring + "' WHERE code =" + mcode;
    Thanks

    the cleanest and easiest soln is to use preparedStatement.
    PreparedStatement ps = con.prepareStatement("update table comment=? where id = ?");
    ps.setString(1,"That's way to do it");
    ps.setInt(1,8);//some itn value
    ps.execute();

  • Outlook 2010 apostrophe, single and double quotes are changes to question mark while sending mails to other internet receipient.

    We are using MS Outlook 2010 as our mail client. But we have noticed that whenevr we sent a mail to any other internet mail recipient all the "apostrophe", "single" and "double quotes" have automatically converted to ?. We have
    done almost all the workaround found in this site such as
    1.New a message and focus on the message window > click File > Options > Mail > Spelling and Autocorrect… > Proofing > AutoCorrect Options… > AutoFormat > clear the box before “Straight quotes” with “smart quotes”
    2. Used different encoding. We presently using US-ASCII for outgoing message. etc.
    Need your help to sort out these issues urgently.
    Waiting for a solution.

    Hi,
    What is your account type? IMAP, POP or Exchange?
    Send an email from the webmail, ask the recipient if this issue persists.
    As far as I know, this problem is always related to the encoding for outgoing messages, and here I suggest you try UTF-8:
    Go to File -> Options -> Advanced -> International options -> Uncheck "Automatically select encoding for outgoing messages", then select "Unicode (UTF-8)" beside "Preferred encoding for outgoing messages" -> OK.
    Hope this helps.
    Regards,
    Melon Chen
    TechNet Community Support

  • Any way to generate a single quote (') with XSLT?

    Hi:
    I guess this is really an XSLT question. I'm using the Transform() method of an XMLType variable to apply a style sheet. The XML in the variable is just something simple like
    <TBL>
    <LAST_NAME>LIKE|JONES</LAST_NAME>
    <FIRST_NAME>=|MARY</FIRST_NAME>
    <AGE>=|50</AGE>
    </TBL>
    I am trying to get a stylesheet to transform something like the above into SQL such as
    Select * from foo where LAST_NAME like 'JONES'
    and FIRST_NAME ='MARY'
    and AGE = 50But to do this, I need to generate the single quotes around the search terms and I can't get anything but LAST_NAME LIKE &apos;JONES&apos;. Is there a way to do this? For now I am generating a ~ and replacing ~ for ' throughout the generated SQL text but that's a pretty sorry solution.
    I thought that something like <xsl:text disable-output-escaping="yes">&amp;</xsl:text> was going to work but then found out it has been deprecated. I was thinking character-map might work but that's an XSLT 2.0 thing and apparently 10g is on XSLT 1.0? In any case, it had no idea what I was trying to do with a character map.
    So, am I overlooking an obvious way to get my stylesheet to insert apostrophes?
    Thanks.

    It's 10.2.0.4.
    Here's the procedure that accepts the XML/XSL clobs and tries to produce a SQL statement.
    PROCEDURE GetSQLQueryFromXML(XMLClob in CLOB, XSLStylesheet in CLOB,
                SQLQuery out CLOB, status out integer) IS
        -- Define the local variables
      xmldata               XMLType;  -- The XMLType format of the XML to transform
      xsldata               XMLType;  -- The XMLType format of the stylesheet to apply
      sqlQuery_XMLType      XMLType;  -- The XMLType format of the SQL query.
      v_SQLQuery            Clob;     -- Holds XML Clob before translating ~ to '
    BEGIN
    status := -1;  -- Initially unsuccessful
      -- Get the XML document using the getXML() function defined in the database.
      -- Since XMLType.transform() method takes XML data as XMLType instance,
      -- use the XMLType.createXML method to convert the XML content received
      -- as CLOB into an XMLType instance.
      xmldata := XMLType.createXML(XMLClob);
      -- Get the XSL Stylesheet using the getXSL() function defined in the database.
      -- Since XMLType.transform() method takes an XSL stylesheet as XMLType instance,
      -- use the XMLType.createXML method to convert the XSL content received as CLOB
      -- into an XMLType instance.
      xsldata := XMLType.createXML(XSLStylesheet);
      -- Use the XMLtype.transform() function to get the transformed XML instance.
      -- This function applies the stylesheet to the XML document and returns a transformed
      -- XML instance.
      sqlQuery_XMLType := xmldata.transform(xsldata);
      -- Return the transformed XML instance as a CLOB value.   
      v_SQLQuery := sqlQuery_XMLType.getClobVal();
      -- Change tildas to apostrophes.  Currently unable to get an XSLT transformation
      -- to insert single quotes, so we're inserting ~ instead.  Now we need to
      -- translate all ~s to 's in our query.
      SQLQuery := translate(to_char(v_SQLQuery),'~','''');
      status := 1; -- Everything went fine to get here
    EXCEPTION
      WHEN OTHERS THEN         
        raise_application_error
        (-20102, 'Exception occurred in GetSQLQueryFromXML :'||SQLERRM);
    END GetSQLQueryFromXML;The XML it works off of is
        someXML CLOB :=
        to_clob('<?xml version="1.0" encoding="windows-1252" ?>
    <variable table_name="SOME_PERSON_TABLE" query_type="PERSON">
      <item>
        <fieldName><![CDATA[PERSON_KEY]]></fieldName>
        <criteria><![CDATA[=]]></criteria>
        <fieldType><![CDATA[Integer]]></fieldType>
        <value><![CDATA[123456789]]></value>
      </item>
      <item>
        <fieldName><![CDATA[LAST_NAME]]></fieldName>
        <criteria><![CDATA[=]]></criteria>
        <fieldType><![CDATA[String]]></fieldType>
        <value><![CDATA[DOE]]></value>
      </item>
      <item>
        <fieldName><![CDATA[FIRST_NAME]]></fieldName>
        <criteria><![CDATA[=]]></criteria>
        <fieldType><![CDATA[String]]></fieldType>
        <value><![CDATA[JOHN]]></value>
      </item>
      <item>
        <fieldName><![CDATA[MIDDLE_NAME]]></fieldName>
        <criteria><![CDATA[-]]></criteria>
        <fieldType><![CDATA[String]]></fieldType>
        <value />
      </item>
      <item>
        <fieldName><![CDATA[SUFFIX]]></fieldName>
        <criteria><![CDATA[-]]></criteria>
        <fieldType><![CDATA[String]]></fieldType>
        <value />
      </item>
    </variable>');And the corresponding XSLT that should translate it is:
      myStylesheet  CLOB :=
      to_clob('<?xml version="1.0" encoding="ISO-8859-1"?>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <!-- <xsl:preserve-space elements="list-of-element-names"/> -->
      <!-- We just want the SQL text output.  No XML declaration etc. -->
      <xsl:output method="text" omit-xml-declaration="yes" indent="no"/>
    <!-- Apostrophes will be made tildas and the PL/SQL will translate those to -->
    <!-- apostrophes for the final SQL string. -->
    <xsl:variable name="apos">~</xsl:variable>
      <xsl:template match="/">
        select * from
        <xsl:value-of select="variable/@table_name"/>
        where 1=1
        <xsl:for-each select="variable/child::node()">
          <xsl:choose>
            <!-- if the value node is not null... -->
            <xsl:when test="./value/text()[normalize-space(.)]">
            <!-- There is another predicate.  Add the AND term and the predicate -->
              AND <xsl:value-of select="./fieldName"/>
              <xsl:text> </xsl:text>
              <xsl:value-of select="./criteria"/>
              <xsl:text> </xsl:text>       
              <xsl:choose>
                <xsl:when test="string(./fieldType)=''String''">
                  <xsl:copy-of select="$apos" />
                  <xsl:value-of select="./value"/>
                  <xsl:copy-of select="$apos" />
                </xsl:when>         
                <xsl:when test="string(./fieldType)=''Clob''">
                  <xsl:copy-of select="$apos" />
                  <xsl:value-of select="./value"/>
                  <xsl:copy-of select="$apos" />
                </xsl:when>
                <xsl:otherwise>
                  <xsl:value-of select="./value"/>
                </xsl:otherwise>
              </xsl:choose>
            </xsl:when>
          </xsl:choose>
        </xsl:for-each>
      </xsl:template>
    </xsl:stylesheet>');Basically if the VALUE element has a value then the fieldType is checked. If fieldType is String or Clob then we'll need the apostrophes. For now I'm putting in tildas and changing them later.

  • Replace a string single quote(') with underscore(_)

    I have more than 100 tables in a schema.
    I have to find out if a string has a single quote in the column and replace it with an underscore.
    I have 2 columns CREATE_USER and UPDATE_USER in all the tables. Now i want to update the values if the string has a single quote in it.
    I tried it with execute immediate but it is not allowing underscore in the statement.
    DECLARE
       v_table_name    VARCHAR2 (30);
       v_column_name   VARCHAR2 (30);
       CURSOR c_name
       IS
          SELECT DISTINCT table_name, column_name
                     FROM user_tab_cols
                    WHERE column_name IN ('LOGIN', 'CREATE_USER', 'UPDATE_USER')
                      AND table_name NOT LIKE '%JN';
    BEGIN
       FOR rec IN c_name
       LOOP
          v_table_name     := rec.table_name;
          v_column_name    := rec.column_name;
          EXECUTE IMMEDIATE    'update '
                            || v_table_name
                            || ' set '
                            || v_column_name
                            || ' = REPLACE('
                            || v_column_name
                            || ','''',"_") where '
                            || v_column_name
                            || ' like "%''%"';
       END LOOP;
    END;
    /i am getting the below error:
    ORA-00904: "%'%": invalid identifier
    ORA-06512: at line 17Can anyone let me know what is the error in the statement and how to overcome it

    please try to replace your execute immediate with:
    EXECUTE IMMEDIATE  'update '
                            || v_table_name
                            || ' set '
                            || v_column_name
                            || ' = REPLACE('
                            || v_column_name
                            || ','''''''',''_'') where '
                            || v_column_name
                            || ' like ''%''''%''';You can check the statement when you take a look at the construction before like this:
    declare
      v_sql varchar2(1000);
    begin
       v_sql:= 'update '
                            || v_table_name
                            || ' set '
                            || v_column_name
                            || ' = REPLACE('
                            || v_column_name
                            || ','''''''',''_'') where '
                            || v_column_name
                            || ' like ''%''''%''';
       dbms_output.put_line(v_sql);
       execute immediate v_sql;
       ...Edited by: hm on 23.11.2010 01:43

Maybe you are looking for