有张表SUMBMIT 表中有字段ID
SendCount
SPNumber
UserNumber
MsgContent
SendFlag
现在想每次取top 100 数据,取出的同时把sendflag字段变为1,问题是现在外面有线程在不定时的往表中插入数据。
怎么样才能取出这前100条数据的同时把sendflag的字段值改变。(后台有线程在定时检测表,把sendflag为1的数据删除并插入到历史表中)

解决方案 »

  1.   

    1.先读到临时表,再根据ID更新原表
    2.用UPDATE的OUTER功能,在更新的同时显示出来这个题昨天问过吧
      

  2.   

    UPDATE SUMBMIT SET SENDFLAG=1 WHERE ID IN (SELECT TOP 100 ID FROM SUMBMIT ORDER BY ID)??
      

  3.   


    现在的问题是外面有程序在不定时的往表里插入数据,如果update后有数据立刻插入,这样取到的数据就不是原先的前100条数据了
      

  4.   

    --这个表应该有主键吧?
    --先把数据取出来放到临时表里
    select top 100 * into #temp from SUMBMIT
    --然后更新数据
    update SUMBMIT set SendFlag=1 from #temp where SUMBMIT.主键=#temp.主键
    --再把数据从临时表取出来。
    select  * from #temp
    --删掉临时表
    drop table #temp
      

  5.   

    select top 100 * into # from sumbmit
    update a set a.sendflag=1 from sumbmit join # on a.字段=b.字段
    drop table #
      

  6.   

    参考我的blog
    SQLServer2005的查询独占模拟
    http://blog.csdn.net/jinjazz/archive/2009/09/04/4520802.aspx以下是测试代码,原理看原文
    set   nocount   onuse tempdb
    go
    if (object_id ('tb' ) is not null )
        drop table tb
    go
    create table tb (id int identity (1 , 1 ), name varchar (10 ), tag int default 0 )
    insert into tb (name ) select 'a'
    insert into tb (name ) select 'b'
    insert into tb (name ) select 'c'
    insert into tb (name ) select 'd'
    insert into tb (name ) select 'e'
    go
    update top (2 ) tb with (rowlock , readpast )  set tag = 1 output inserted . id , inserted . name where tag = 0
    go
    update top (2 ) tb with (rowlock , readpast ) set tag = 1 output inserted . id , inserted . name where tag = 0
    go
    update top (2 ) tb with (rowlock , readpast ) set tag = 1 output inserted . id , inserted . name where tag = 0
    go
    set nocount off/*
    id          name
    ----------- ----------
    1           a
    2           bid          name
    ----------- ----------
    3           c
    4           did          name
    ----------- ----------
    5           e*/