用一个表a更新另外一个表b:
条件:a.id=b.id 如果a中有对应的记录就用b的更新a表,如果a表没有对应的记录就插入。
Merge into postaa
Using postb b
On (a.post_id=b.post_id)
When matched then
Update set a.name=b.name,a.channel_id=b.channel_id
When not matched then
Insert into (post_id,name,channel_id)
Values(b.post_id,b.name,b.channel_id);
Oracle9i SQL ref里,没有找到Upsert。
Oracle10i SQL ref里,找到Upsert,如下:
The next example creates a multidimensional array from sales_view with columns containing country, product, year, and sales. It also:
Assigns the sum of the sales of the Mouse Pad for years 1999 and 2000 to the sales of the Mouse Pad for year 2001, if a row containing sales of the Mouse Pad for year 2001 exists.
Assigns the value of sales of the Standard Mouse for year 2001 to sales of the Standard Mouse for year 2002, creating a new row if a row containing sales of the Standard Mouse for year 2002 does not exist.
SELECT country,prod,year,s
FROM sales_view
MODEL
PARTITION BY (country)
DIMENSION BY (prod, year)
MEASURES (sale s)
IGNORE NAV
UNIQUE DIMENSION
RULES UPSERT SEQUENTIAL ORDER
(
s[prod='Mouse Pad', year=2001] =
s['Mouse Pad', 1999] + s['Mouse Pad', 2000],
s['Standard Mouse', 2002] = s['Standard Mouse', 2001]
)
ORDER BY country, prod, year;
you can wirte like this in pl/sql:
update table set ... where ...;
if sql%nofound then
insert into table ...
;
Oracle9i Implementation:
In Oracle9i, the MERGE statement INSERTS and UPDATES the data with a single SQL statement.
MERGE INTO SALES_FACT D
USING SALES_JUL01 S
ON (D.TIME_ID = S.TIME_ID
AND D.STORE_ID = S.STORE_ID
AND D.REGION_ID = S.REGION_ID)
WHEN MATCHED THEN
UPDATE
SET d_parts = d_parts + s_parts,
d_sales_amt = d_sales_amt + s_sales_amt,
d_tax_amt = d_tax_amt + s_tax_amt,
d_discount = d_discount + s_discount
WHEN NOT MATCHED THEN
INSERT (D.TIME_ID ,D.STORE_ID ,D.REGION_ID,
D.PARTS ,D.SALES_AMT ,D.TAX_AMT ,D.DISCOUNT)
VALUES (
S.TIME_ID ,S.STORE_ID ,S.REGION_ID,
S.PARTS ,S.SALES_AMT ,S.TAX_AMT ,S.DISCOUNT);