SQL Server 2005带WHILE循环的插入
我想得到这样的结果 这是我的密码SQL Server 2005带WHILE循环的插入,sql,sql-server,sql-server-2005,Sql,Sql Server,Sql Server 2005,我想得到这样的结果 这是我的密码 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
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
declare@current int
声明临时表(c1 int、c2 int、c3 int、c4 int、c5 int、c6 int、c7 int、c8 int、c9 int、c10 int)
选择@current=1
而@current
没有理由使用while
循环。通常,在使用SQL时,您应该以基于集合的方式思考,而不是以迭代的方式
没有理由使用while
循环。一般来说,在使用SQL时,您应该以基于集合的方式思考,而不是以迭代的方式思考。无需而循环即可
Insert into @temp(c1,c2,c3,.c10)
select @current-1,@current,@current+1,..@current+9
无需while
循环即可执行此操作
Insert into @temp(c1,c2,c3,.c10)
select @current-1,@current,@current+1,..@current+9
我会避免,而在这种情况下使用插入。。。使用交叉连接进行选择
:
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关键字/语句):
go 10
执行当前SQL Server批处理十次。我会避免,而在这种情况下使用插入。。。使用交叉连接进行选择
:
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关键字/语句):
go 10
执行当前SQL Server批处理十次