关于同时添加和更新一个表

博客主要介绍了用表b更新表a的操作,若a中有对应记录则用b更新,无则插入。还给出了Oracle 9i和10i中相关SQL语句示例,如Merge语句及Upsert用法,也提及了pl/sql中更新和插入的实现方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用一个表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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值