2017-07-02 77 views
1

这里我有两个表,名称表A和B表如何插入表中的记录范围,当我在SQL Server中定义第一个表的范围内2012

表A

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

表B

ID  Numbers 
--------------------------- 
1   985 
2   986 
3   987 
4   988 
5   989 
6   990 
7   991 
8   992 
9   1201 
10   1202 
11   1203 
12   1204 
13   1205 
14   1206 

和数量是这样的。表格结构也是如此。

如何插入这样的数据。正如我在表格从125至135定义的范围,都在这个范围内的数量必须在表B.

回答

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 @[email protected] 
while @number<[email protected] 
begin 
    insert into sampleB (id, numbers) values (@id,@number); 
    set @[email protected]+1 
end 

最后问题解决了。在表A中插入数据范围后,数据将自动插入表B中。

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; 
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 
+0

值重复,而我插入第二次与新的记录。旧值正在重复 –

+0

我明白了。我不知道那个要求,所以我只是做了“插入”部分。很高兴你提出了一个答案。 –

+0

谢谢切斯特林,您的宝贵建议 –

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选项。
  • 您可以像创建新表一样方便地插入值。
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 
+0

没有奏效。 alys说必须定义标量变量@t –

+0

你使用的是什么版本的sql server? – KumarHarsh

+0

sql server 2012 –