当我在SQL Server 2012中的第一个表中定义范围时,如何在表中插入范围的记录

时间:2017-07-02 21:13:02

标签: sql sql-server range

这里我有两个表,名称为表A和表B.

表A

streamplot

表B

ID    From     To  
-------------------
1     985      992
2     1201     1207
3     1584     1589

,数字就是这样的。还有表结构。

如何插入此类数据?当我在表A中定义125-135的范围时,必须在表B中插入此范围内的所有数字。

5 个答案:

答案 0 :(得分:1)

感谢所有的好心人提出宝贵的建议。使用触发器解决了问题。

CREATE TRIGGER trgAfterInsert on samplea
FOR INSERT
AS declare @id int, @from bigint, @to bigint, @number bigint;

select @id=i.id from inserted i;
select @from=i.fromnum from inserted i;
select @to=i.tonum from inserted i;

set @number=@from
while @number<=@to
begin
    insert into sampleB (id, numbers) values (@id,@number);
    set @number=@number+1
end

最后问题解决了。使用表A中的插入数据范围,数据将通过此触发器自动插入表B中。

答案 1 :(得分:0)

您可以使用游标和while循环

来完成
DELCARE @Uid int, @Ustart int, @Uend int, @Ucounter;
DECLARE Ucursor CURSOR  
FOR SELECT * FROM TableA  ;
OPEN vend_cursor  
FETCH NEXT FROM Ucursor
INTO @Uid,@Ustart,@Uend

WHILE @@FETCH_STATUS = 0  
BEGIN 
    SET @Ucounter = @Ustart
    WHILE @Ucounter <> @Uend
       BEGIN
       INSERT INTO TableB
       VALUES (@Ucount) -- Set the identity on for id
       SET @Ucounter += 1
       END
    FETCH NEXT FROM Ucursor
    INTO @Uid,@Ustart,@Uend
END
CLOSE Ucursor;

答案 2 :(得分:0)

不确定这是否有效但是有效。

DECLARE @range INT = (SELECT [To] - [From] FROM @tableA WHERE [Id] = 1)
DECLARE @count INT = 0

WHILE (@count <= @range)
BEGIN
    INSERT INTO @tableB 
        SELECT [From] + @count FROM @tableA
    SET @count = @count + 1
END

答案 3 :(得分:0)

我建议使用递归CTE:

with cte as (
      select from as n, from, to
      from a
      union all
      select n + 1, from, to
      from cte
      where n < to
     )
select n
from cte;

要创建表格,您可以执行以下操作:

with cte as (
      select from as n, from, to
      from a
      union all
      select n + 1, from, to
      from cte
      where n < to
     )
select identity(), n
into b
from cte;

注意:

  • 我保留了列名,而没有转义它们。显然,fromto是SQL中的关键字。
  • 如果您的差距超过100,则需要使用MAXRECURSION选项。
  • 您可以像创建新表一样轻松地插入值。

答案 4 :(得分:0)

试试这个,

declare @t table(ID int,Froms int,Tos  int)

insert into @t values
(1   , 985   ,  992  )
,(2   , 1201  ,  1207 )
,(3   , 1584  ,  1589 )

declare @table2  table(id int identity(1,1),numbers int)
insert into @table2
select number from @t t
cross apply(
select distinct number from master..spt_values
where number>t.[froms]   and number<=t.tos)ca

select * from @table2