开发者

How to update top n rows dynamically?

I have a table with similar rows...like

PartNo  SerialNo  Inven_Qty  Status
------  开发者_StackOverflow社区--------  ---------  ------
001A    NULL      1          IN
001A    NULL      1          IN
001A    NULL      1          IN
001A    NULL      1          IN

Now I want to update the rows dynamically..I have a web page where I enter PartNo and the value of items which are OUT...ex 2 items are OUT...I want to update 2 rows with Inven_Qty 0 and status as OUT....Can anyone please tell me how to do this???

Thanks in advance.


Based on Mikael Eriksson, for Oracle:

update YourTable
  set Inven_Qty = 0,
      Status = 'OUT'
where PartNo = '001A'
  and Status = 'IN'
  and rownum<=3

(for 3 items to update)


This syntax works for SQL Server. Might work for other DBMS as well.

update top (2) YourTable
set Inven_Qty = 0,
    Status = 'OUT'
where PartNo = '001A' and
      Status = 'IN'

Another way that may be more easily translated to a some other DBMS

with C as
(
  select Inven_Qty,
         Status,
         row_number() over(order by (select 1)) as rn
  from @T
  where PartNo = '001A' and
        Status = 'IN'
)
update C
set Inven_Qty = 0,
    Status = 'OUT'
where rn <= 2


You can do it like this.

UPDATE table_name
SET Status = "OUT", Invent_QTY = 0,
WHERE PartNo = "<part number>" AND SerialNo = <serial number>


It would probably be better if you could use 'SerialNo' in the query, but if not you can try:

update <your table> set Status='OUT', Inven_Qty=0 where rowid in 
    (select rowid from <your table> where Status=IN and Inven_Qty=1
        and PartNo=<part number> where rownum <= <some value>)

But this only works if you assume that Inven_Qty is either 1 or 0. If Inven_Qty can be greater than 1 I don't think you can even do this with just a single query.

EDIT: This won't work if SerialNo is null. You have to have some sort of unique id for this to work. If you don't you should add one. If you're working on oracle you can use ROWID.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜