如何根据序列从另一个表更新?

时间:2013-03-04 06:42:40

标签: tsql sql-server-2005

我设法得到了这个: How to get the end of entry of the first column in TSQL?

更新的数据如下,并设法获取最后一条记录并进行了更新。

Service; Sequence; EndSequence  
A, 2089697; 2089737
B, 2089738; 2089837
C, 2089838; 2090367
D, 2090368; 2090399
E, 2090400; 2090500

现在我想根据ID上的序列开始和结束开始更新主表上有100万条记录。我可以通过光标来做到这一点,但我更喜欢通过普通查询。

BTW我正在使用SQL 2005。

Master表格如下:

ID; Value; Service
2089697; 23; null
...
2090500; 12; null

所以结果将是:

ID; Value; Service
2089697; 23; A
... 
2089737; 45; A
2089738; 45; B
...
2089837; 34; B 
2089838; 23; C
...

由于

1 个答案:

答案 0 :(得分:1)

这里有多个选项。

  1. 相关子查询:

    UPDATE MasterTable
    SET Service = (
      SELECT s.Service
      FROM SequenceTable s
      WHERE MasterTable.ID BETWEEN s.Sequence AND s.EndSequence
    )
    WHERE Service IS NULL
    ;
    
  2. 内部联接:

    UPDATE MasterTable
    SET Service = s.Service
    FROM SequenceTable s
    WHERE MasterTable.Service IS NULL
      AND MasterTable.ID BETWEEN s.Sequence AND s.EndSequence
    ;
    

    替代语法:

    UPDATE m
    SET Service = s.Service
    FROM MasterTable m
    INNER JOIN SequenceTable s
      ON m.ID BETWEEN s.Sequence AND s.EndSequence
    WHERE m.Service IS NULL
    ;
    
  3. 两个选项都假设SequenceTable中的范围不重叠。