简体   繁体   中英

How to remove both leading and trailing spaces within a group of data in Oracle11gR2?

I am looking for a means of removing leading and trailing spaces based on the following scenario within an Oracle 11gR2 DB using SQL. Not sure if I require REGEXP_REPLACE.

At the moment I have the following possible scenario:

v_entries := '"QAZ   "," QWERTY     ","BOB ","   MARY        ","HARRY","  TOM JONES  "'

where you can see that I have both leading as well as trailing spaces within some of data within the double quotes, ie " QWERTY " but not all like "HARRY" , which is fine.

What I am after and unsure how to do in Oracle 11gR2 is this result, ie:

v_entries := '"QAZ","QWERTY","BOB","MARY","HARRY",,"TOM JONES"'

where all leading/trailing spaces have been removed, where they exists within the double quote groupings but only from the beginning and ends of each grouping.

Groups that have spaces within the actual values, should not be removed, just like my "TOM JONES" - want to preserve the given name space surname value here.

Assuming you don't want to split the string into its components, you can use a regular expression to remove the spaces. If you want to get rid of all spaces - so you don't have any two-word values, for example - then you can use:

v_entries := regexp_replace(v_entries, '[[:space:]]', null);

But if you might have spaces in the middle of a value that you want to preserve you can only remove those either side of a double-quote character:

v_entries := '"QAZ   "," QWERTY     ","BOB ","   MARY            ","HARRY"';

For example:

declare
  v_entries varchar2(80);
begin
  v_entries := '"QAZ   "," QWERTY     ","BOB ","   MARY           ","TOM JONES"';
  v_entries := regexp_replace(v_entries, '[[:space:]]*"[[:space:]]*', '"');
  dbms_output.put_line(v_entries);
end;
/

anonymous block completed
"QAZ","QWERTY","BOB","MARY","TOM JONES"

You should use the trim() function to remove leading and trailing spaces. Here's the documentation on how to use trim() .

Combining the LRTIM and RTRIM would do the trick

SELECT RTRIM(LTRIM ('   QWERTY   ') ) FROM DUAL;

In PLSQL

DECLARE
   check varchar2(30) := '   QWERTY   ';
BEGIN
   dbms_output.put_line(RTRIM(check));
   dbms_output.put_line(LTRIM(check));
   dbms_output.put_line(RTRIM(LTRIM (check)));
END;
/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM