gpt4 book ai didi

sql - 从表中插入或更新

转载 作者:行者123 更新时间:2023-12-03 03:22:57 25 4
gpt4 key购买 nike

我需要从另一个表插入多条记录,并且如果存在重复键,则更新同一个表中的当前记录。

我在这个网站上找到了几个有用的答案,但似乎没有一个对我有用。全部返回语法错误,我不确定是否只是我使用的接口(interface)不支持这些命令或什么。在没有重复键的地方插入,这个查询工作正常。如果有任何人可以告诉我可以使用什么语法来正确执行给定的这些命令,我​​将非常感激!

以下这些似乎完全符合我的需要,但没有起作用。

REPLACE INTO
INSERT ... ON DUPLICATE KEY UPDATE
INSERT OR REPLACE INTO

以下是我的 INSERT 查询当前的示例:

<小时/>
USE database
GO
INSERT INTO products
(upc, name, price)
select upc = TempTables.dbo.new_items.upc,
name = TempTables.dbo.new_items.name,
price = TempTables.dbo.new_items.price
FROM TempTables.dbo.new_items

最佳答案

我个人喜欢 MERGE 语句

create table ##new_items (upc int, name int, price int)

create table ##products
(upc int, name int, price int)

merge into ##products [tgt]
using ##new_items [src]
on [tgt].upc = [src].upc and [tgt].name = [src].name
when matched then update set price = [src].price
when not matched then insert (upc, name, price)
values ([src].upc, [src].name, [src].price)
;

要查看您正在使用的项目,您可以像这样查询

-- the items in new_items that aren't in products
select n.* from new_items n left outer join products p
on n.upc = p.upc where p.upc is null

-- the items in new_items that are in products
select n.* from new_items n left outer join products p
on n.upc = p.upc where p.upc is not null

当然,一旦运行更新/插入/合并,您将不知道哪些项目已经存在以及哪些项目已插入。如果您想知道,则需要向表中添加“更新日期”列并在那时进行标记。

关于sql - 从表中插入或更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22510763/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com