从sql表中获取值并分配给另一个表中的行

时间:2014-01-12 04:00:41

标签: sql sql-server-2008 foreach

好吧,我以为我自己解决了这个问题,直到我尝试了,在SQL 2008中工作。

我有两个表,table1有一个列,有几千个(可用的)ID。表2每天都会刷新一组新用户,这些用户需要分配Table1中的其中一个ID。

然后我需要从Table1中删除该ID,以便不重新分配。我遇到的问题是我不知道如何通过table2中的行(通常小于50)进行循环并从table1分配下一个最低的ID?建议表示赞赏!我的下面的代码选择了正确的值,但我的更新语句只是将所有值更新为table1中的最低值,那么每行如何“冲洗并重复”?

DECLARE @nextid int
SET @nextid = (SELECT uid FROM table1
WHERE uid = (SELECT MIN(uid) FROM table1))

UPDATE table2 
SET uid = @nextid
WHERE uid IS NULL

DELETE FROM usable_ids
WHERE uid = @nextid

表1

+------+
| uid  |  
+-------
| 555  |
| 556  |
| 557  |
| 558  | 
| 559  |
| 560  |
+------+

表2

+---------+--------+-----------+
| UID     | Status | hire_date | 
+---------+--------+-----------+
|         | happy  | 10/10/2005|
|         | sad    | 12/01/2009|
+---------+--------+-----------+

谢谢!

1 个答案:

答案 0 :(得分:3)

这是一个想法。为每个id分配一个序列号,然后使用它将id分配给已知的槽。然后,从表中删除相应的ID:

declare @NumToDelete int;
select @NumToDelete = count(*) from table1 where uid is null;

with toupdate as (
      select t2.*, row_number() over (order by newid()) as seqnum
      from table2
      where uid is null
     )
update tu
    set uid = t1.uid
    from toupdate tu join
         (select t1.uid, row_number() over (order by uid) as seqnum
          from table1
         ) t1
         on t1.seqnum = tu.seqnum;

with todelete as (
      select t1.*, row_number() over (order by uid) as seqnum
      from table1
     )
delete from todelete where seqnum <= @NumToDelete;

为了记录,我认为最好将table1中的记录标记为删除,而不是使用delete删除它们。