繁体   English   中英

带WHILE LOOP的SQL Server 2005插入

[英]SQL Server 2005 Insert with WHILE LOOP

我想得到这样的结果

在此处输入图片说明

这是我的代码

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

如何插入? 谢谢你的帮助。

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时,应该以基于集合的方式而不是迭代的方式进行思考。

无需while循环即可执行此操作

Insert into @temp(c1,c2,c3,.c10)
select @current-1,@current,@current+1,..@current+9

我会避免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)

或(在sqlcmd / SSMS内 )使用GO (此关键字不是T-SQL关键字/语句):

insert into dbo.TargetTable (...columns...)
values (...)
go 10 

执行go 10执行当前SQL Server批处理十次。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM