我想得到像这样的结果
这是我的代码
declare @current int
declare @Temp Table(c1 int, c2 int, c3 int, c4 int, c5 int, c6 int, c7 int, c8 int, c9 int, c10 int)
select @current = 1
while @current <= 10
begin
--I want to insert here
select @current = @current + 1
end
select * from @Temp
我该如何插入?谢谢你的帮助。
答案 0 :(得分:1)
insert into @temp(c1, c2, c3, c4, c5, c6, c7, c8, c9, c10)
select 1, 2, 3, 4, 5, 6, 7, 8, 9, 10;
没有理由使用while
循环。通常,在使用SQL时,您应该以基于集合的方式而不是迭代方式进行思考。
答案 1 :(得分:1)
不需要while
循环来执行此操作
Insert into @temp(c1,c2,c3,.c10)
select @current-1,@current,@current+1,..@current+9
答案 2 :(得分:0)
在这种情况下,我会使用WHILE
:
INSERT ... SELECT with CROSS JOIN
declare @Temp Table(c1 int, c2 int, c3 int, c4 int, c5 int, c6 int, c7 int, c8 int, c9 int, c10 int)
insert into dbo.TargetTable (...columns...)
select t.*, n.Num
from @Temp t
cross join (
select 1 union all
select 2 union all
select 3 union all
select 4 union all
select 5 union all
select 6 union all
select 7 union all
select 8 union all
select 9 union all
select 10
) n(Num)
使用GO
或(在 sqlcmd / SSMS 内)(此关键字不是T-SQL关键字/语句):
insert into dbo.TargetTable (...columns...)
values (...)
go 10
go 10
执行当前SQL Server批次十次。