选择并更新所需的语句帮助

时间:2016-06-03 20:01:13

标签: sql oracle select sql-update

情境:

我有两个表:Vendors表提供唯一标识符;并且Order表包含的行包含一个列,该列具有我们想要剥离的唯一标识符。例如:唯一ID:12345,内容有"订购12345" ...期望的结果,字面意思:"订购XXXXX"

我需要一个select语句来显示表2中哪些记录实际上有唯一标识符和更新语句来进行剥离。

模式

Table Vendors
    ID   varchar2(9)
    NAME varchar(50)

Table Orders
    OrderNumber varchar2(10)
    Dscr        varchar(250) <----order description

示例:

Vendors
12345 Joe
23456 Jenni

Orders
A123456 | Order for 12345 <---notice this number is the ID of the Vendor
B039483 | Order for 23456

期望的结果:

Orders 
    A123456 | Order for XXXXX
    B039483 | Order for XXXXX

到目前为止我有什么:

DECLARE  
  TYPE dscr_type IS TABLE OF VARCHAR2(250);
  chk_dscr_coll dscr_type;

BEGIN 
  -- gather a list of IDs to use
  FOR someone IN (
    SELECT unique(ID) FROM vendors WHERE TIN IS NOT NULL
  )

  -- loop through the Orders table
  -- try to match the ID agains each record via regular expression

  LOOP
    SELECT dscr BULK COLLECT INTO dscr_coll
    FROM orders
    WHERE REGEXP_LIKE(dscr, '.*'||someone.ID||'.*');
    DBMS_OUTPUT.PUT_LINE('>>>>>>>>>>>>>>'||dscr_coll(1));

  END LOOP;
  EXCEPTION 
    WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE('');
END;
/

更新

我跟随Kordirko提供的线索并提出了这个MERGE声明。

MERGE INTO AFMOWN.ABS_DOC_ACTG target
USING (
   SELECT v.TIN 
   FROM AFMOWN.R_VEND_CUST v
   where v.TIN is not null
) vendor
ON (chk_dscr LIKE '%' || vendor.TIN || '%')
WHEN MATCHED THEN UPDATE
SET chk_dscr = REGEXP_REPLACE( chk_dscr, vendor.TIN, '999999999' );

不幸的是,我收到了这个错误: UPDATE SET的LHS包含ON子句

中引用的列

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

您不需要PL / SQL代码。假设订单号需要替换为&#39; XXXXX&#39;你可以这样做:

update orders set dscr = regexp_replace(dscr, '\d+', 'XXXXX')

答案 1 :(得分:0)

尝试MERGE声明:

MERGE INTO Orders
USING (
   SELECT v.id FROM Vendor v
   JOIN Orders o
   ON v.descr LIKE '%' || v.id || '%'
) x
WHEN MATCHED THEN UPDATE
SET descr = REPLACE( descr, x.id, 'XXXXX" )
;