+ -
当前位置:首页 → 问答吧 → 分批次更新同一个表中的相同字段,急!!!

分批次更新同一个表中的相同字段,急!!!

时间:2011-12-04

来源:互联网

表名为:COMUST
表结构如下:
Pnumber name Bchno Pset Pact
  1 HB500 7901 2404 2369
  1 HC300 7901 560 578
  1 water 7901 344 349
  1 HB500 7902 2422 2479
  1 HC300 7902 542 547
  1 water 7902 339 372



Pnumber 为主键,我想同时更新Bchno 为 7901,name为HB500, Bchno 为 7902,name为HB500的Pact值,并且Bchno 为 7901,name为HB500这条记录的Pact值更新为2404,Bchno 为 7902,name为HB500这条记录的Pact值更新为2422,用SQ语句该怎么做呢?


请教各位高手,很急啊,万分感谢!!!

作者: Nong_Ming_Shuai   发布时间: 2011-12-04

SQL code
update tb set pact=2404 where (bchno =7901 and name='HB500')
update tb set pact=2422 where (bchno =7902 and name='HB500')

作者: ssp2009   发布时间: 2011-12-04

SQL code
update 
   a
set
   Pact=b.Pset
from 
   tb a,
   (select px=ROW_NUMBER()over(partition by Bchno order by GETDATE()),* from tb)b
where
  a.Bchno=b.Bchno and a.Pnumber=b.Pnumber
and
  b.px=1
  
select * from tb 

作者: fredrickhu   发布时间: 2011-12-04

SQL code
----------------------------------------------------------------
-- Author  :fredrickhu(小F,向高手学习)
-- Date    :2011-12-04 20:14:30
-- Version:
--      Microsoft SQL Server 2008 (RTM) - 10.0.1600.22 (Intel X86) 
--    Jul  9 2008 14:43:34 
--    Copyright (c) 1988-2008 Microsoft Corporation
--    Enterprise Evaluation Edition on Windows NT 5.1 <X86> (Build 2600: Service Pack 3)
--
----------------------------------------------------------------
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
go 
create table [tb]([Pnumber] int,[name] varchar(5),[Bchno] int,[Pset] int,[Pact] int)
insert [tb]
select 1,'HB500',7901,2404,2369 union all
select 1,'HC300',7901,560,578 union all
select 1,'water',7901,344,349 union all
select 1,'HB500',7902,2422,2479 union all
select 1,'HC300',7902,542,547 union all
select 1,'water',7902,339,372
--------------开始查询--------------------------
update 
   a
set
   Pact=b.Pset
from 
   tb a,
   (select px=ROW_NUMBER()over(partition by Bchno order by GETDATE()),* from tb)b
where
  a.Bchno=b.Bchno and a.Pnumber=b.Pnumber and a.name=b.name 
and
  b.px=1
  
select * from tb 
----------------结果----------------------------
/* Pnumber     name  Bchno       Pset        Pact
----------- ----- ----------- ----------- -----------
1           HB500 7901        2404        2404
1           HC300 7901        560         578
1           water 7901        344         349
1           HB500 7902        2422        2422
1           HC300 7902        542         547
1           water 7902        339         372

(6 行受影响)
*/

作者: fredrickhu   发布时间: 2011-12-04

热门下载

更多