当前位置: 代码迷 >> Sql Server >> 3条相同记录怎么只update其中1条
  详细解决方案

3条相同记录怎么只update其中1条

热度:15   发布时间:2016-04-24 10:12:15.0
3条相同记录如何只update其中1条
如果数据库存在3条一膜一样的数据,除了主键不同,那么如何只update其中一条数据(随便哪条),
例如 id,码数,出库(bit)
          1,22,0
          2,22,0
update A set 出库=1 where 码数=22 再加上什么条件可以只update其中一条
求解
谢谢诶
------解决方案--------------------
----------------------------------------------------------------
-- Author  :DBA_HuangZJ(發糞塗牆)
-- Date    :2014-08-07 10:59:57
-- Version:
--      Microsoft SQL Server 2012 - 11.0.5058.0 (X64) 
-- May 14 2014 18:34:29 
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition: Core-based Licensing (64-bit) on Windows NT 6.3 <X64> (Build 9600: ) (Hypervisor)
--
----------------------------------------------------------------
--> 测试数据:[A]
if object_id('[A]') is not null drop table [A]
go 
create table [A]([id] int,[码数] int,[出库] int)
insert [A]
select 1,22,0 union all
select 2,22,0
--------------开始查询--------------------------

select * from [A]

UPDATE a
SET a.[出库]=1
FROM (SELECT MAX(id)id,[码数] FROM a GROUP BY [码数]) b 
WHERE a.码数=b.码数 AND a.id=b.id

select * from [A]
----------------结果----------------------------
/*
id          码数          出库
----------- ----------- -----------
1           22          0
2           22          0

(2 行受影响)

(1 行受影响)

id          码数          出库
----------- ----------- -----------
1           22          0
2           22          1 
*/
  相关解决方案