从表中插入或更新

时间:2014-03-19 15:33:20

标签: sql sql-server tsql

我需要从另一个表中插入几个记录,并且在有重复键的地方,而是从同一个表中更新当前记录。

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

这些似乎完全符合我的要求,但没有奏效。

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

3 个答案:

答案 0 :(得分:3)

我个人喜欢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

当然,一旦你运行更新/插入/合并,你就不会知道哪些项目已经存在,哪些项目已经插入。如果您想知道自己需要添加更新日期'列到表并在那时标记。

答案 1 :(得分:0)

  

我需要做的是从另一个表插入多个记录,并且在有重复键的地方,而是从同一个表中更新当前记录。

这通常分两步完成(一些SQL服务器有一个语法可以一步完成,但更通用的方法是两个步骤)

(assuming the key is upc):

UPDATE products
SET name = new_items.name,
    price = new_items.price
FROM products
INNER JOIN new_items
   ON products.upc = new_items.upv 

INSERT INTO products
(upc, name, price)
SELECT 
    upc,
    name,
    price
FROM TempTables.dbo.new_items
WHERE upc NOT IN 
    (SELECT upc FROM products)

答案 2 :(得分:0)

UPDATE products  
SET name = new_items.name, price = new_items.price
FROM products JOIN new_items USING(upc);

INSERT INTO products
(upc, name, price)
SELECT upc, name, price
FROM TempTables.dbo.new_items
WHERE NOT EXISTS (SELECT 1 FROM products WHERE upc = TempTables.dbo.new_items.upc);

考虑到,upc是你的Primary key

如果已存在UPDATE

行,upc in new_items查询将会成功 如果INSERT的行不存在,

upc in new_items查询将会成功。

相关问题