使用唯一ID更新多个行

时间:2017-04-23 11:59:24

标签: sql sql-server

如何更新多行,以便所有行都具有唯一ID?例如:

MyTable:

id/product_id/price/sell_price/amount  
231/122/10/5/6  
276/122/5/3/16  
298/122/20/12/60  
210/122/100/55/1  

现在,如果我将这些值插入临时表

(select * into #tmp_table from MyTable where product_id=122)

现在我想进行一些更改并将这些值重新插入到原始表格中#34; MyTable",但我在这里苦苦挣扎,如何获得唯一的id值?

3 个答案:

答案 0 :(得分:0)

创建表格后,将updatejoin

一起使用
update t
    set ? = tt.?
    from MyTable t join
         #tmp_table tt
         on t.id = tt.id;

目前还不清楚您要设置哪些值,只是将适当的逻辑放在set子句中。

编辑:

根据您的评论。您只需将id列定义为identity列即可。然后:

insert into MyTable (product_id, price, sell_price, amount)
    select product_id, price, sell_price, amount
    from #tmp_table;

如果您愿意,也可以生成新的ID:

insert into MyTable (id, product_id, price, sell_price, amount)
    select x.maxid + row_number() over (order by (select null)) as id,
           tt.product_id, tt.price, tt.sell_price, tt.amount
    from #tmp_table tt cross join
         (select max(id) as maxid from MyTable) x;

但身份识别似乎更符合表格的精神。

答案 1 :(得分:0)

您可以在临时表上使用简单更新或合并

UPDATE y 
    set y.amount = t.amount+100  --your update columns
    from yourProduct y
    inner join #tmp t
    on y.id = t.id and y.product_id = t.product_id

你的桌子

create table yourProduct (id int, product_id int, price int, sell_price int, amount int)

insert into yourProduct (id, product_id, price, sell_price, amount) values
 (231,122,10 ,5 ,6  )
,(276,122,5  ,3 ,16 ) 
,(298,122,20 ,12,60 ) 
,(210,122,100,55,1  )


select * into #tmp from yourProduct where product_id = 122

答案 2 :(得分:0)

建议添加一个增加了产品ID的新列:s。

alter table MyTable add productid Int Identity(1,1)

如果将使用旧产品ID:s,则可以删除旧列。

alter table MyTable drop column product_id

如果您希望使用列的旧名称:

exec sp_rename 'productid', 'MyTable.product_id', 'column';

我强烈建议,当你这样做时,将UNIQUE-constraint添加到此列,以保护自己免受重复的product-id:s。

alter table MyTable
add unique (product_id);
相关问题