【问题标题】:T-SQL inserting record while loopT-SQL 在循环中插入记录
【发布时间】:2016-05-25 20:19:04
【问题描述】:

我想向另一个表 (ten_split) 中插入一条记录,直到该值超过 start_table 中 End_loc 字段中的值。思路是将 start_table 中的记录拆分成 10m 段。

start_table 如下所示:

ID   Start_loc   End_loc
 1    0           40
 2    0           35

我希望基于 start_table 的 ten_split 表如下所示:

UID  ID  start_new  end_new
 1    1   0          10
 2    1   10         20
 3    1   20         30
 4    1   30         40
 5    2   0          10
 6    2   10         20
 7    2   20         30
 8    2   30         40

我正在使用 Microsoft T-SQL。我是使用循环的新手,如果有任何帮助,我将不胜感激。

【问题讨论】:

    标签: sql-server tsql loops while-loop record


    【解决方案1】:

    假设我正确理解了您的问题,因为您使用的是 sql server,您可以使用递归 cte:

    SQL Fiddle

    MS SQL Server 2008 架构设置

    create table start_table (id int, start_loc int, end_loc int);
    
    insert into start_table values (1, 0, 40);
    insert into start_table values (2, 0, 35);
    

    查询 1

    with recursivecte as (
      select id, 0 as start_loc, 10 as end_loc
      from start_table
      union all 
      select s.id, r.start_loc+10, r.end_loc+10
      from start_table s
        join recursivecte r on s.id = r.id
      where r.end_loc < s.end_loc
      )
    select * from recursivecte
    order by id, start_loc
    

    Results

    | id | start_loc | end_loc |
    |----|-----------|---------|
    |  1 |         0 |      10 |
    |  1 |        10 |      20 |
    |  1 |        20 |      30 |
    |  1 |        30 |      40 |
    |  2 |         0 |      10 |
    |  2 |        10 |      20 |
    |  2 |        20 |      30 |
    |  2 |        30 |      40 |
    

    【讨论】:

    • @Benjie98 我只编辑了帖子以重新格式化,您应该接受答案作为已接受的答案,以便 sgeddes 获得信用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多