日期:2014-05-18  浏览次数:20495 次

sql创建语句的问题,求解
现在有两个表,我想从表1中取出一个id,在表2中插入20条包含这个id的记录,如此循环,把表1的id都插1遍,有没有高人指点下呢

------解决方案--------------------
。。。为何要20次,有啥规律?

declare @i int
set @i = 1
while @i <= 20
begin
insert into b select id from a
set @i = @i + 1
end
------解决方案--------------------
SQL code
insert 表2
select 
a.ID
from 表1 as a,(select top 20 ID from syscolumns) as b
where a.ID=a

------解决方案--------------------
双循环
SQL code
declare @id varchar(10),@n int=1 ,@i int=1
while exists(select 1 from (select *,ROW_NUMBER() over(order by getdate()) rid from tb)a where rid=@n)
begin
   select @id=id  from  tb where rid=@n
   while @i<=20
   begin
     insert into b select id from a
     set @i = @i + 1
   end
   set @n=@n+1
end

------解决方案--------------------
declare @id
 declare @cursor_Insert cursor for
 select Id from table1
 open @cursor_Insert
 fetch next from @cursor_Insert into @id
 
 while @@FETCH_STATUS=0
begin
..插入20行数据.
fetch next from @cursor_Insert into @id

end
close @cursor_Insert
deallocate @cursor_Insert
------解决方案--------------------
探讨

抱歉我前面没说清问题,现在补充下
表1为pointhistory表,表结构:id routehistoryid pointname membername
表2为itemhistory表,表结构:id routehistoryid pointhistoryid pointname itemname
现在想从表1中取id(即表2的pointhistoryid)生成20条数据插……

------解决方案--------------------
探讨
表1的内容为id routehistoryid pointname membername
2541 451263252 发电机 李明

现在取id添加到表2中,id routehistoryid pointhistoryid pointname itemname
12345 451263252 2541 发电机 温度1
12456 451263252 2541 发电机 温度2
451256 451263252 2541 发电机 温度3