2017-07-02 75 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 –