不止一次像For循环一样执行SQL语句

不止一次像For循环一样执行SQL语句

问题描述:

我有一个SQL查询(正常的)。我必须连续运行这个查询4次(就像编程中的For循环)。我怎么能有一个像数组的东西,并重复查询执行?不止一次像For循环一样执行SQL语句

SQL服务器

更新:

我更新基于列TargetLocation一些数据。此目标位置的值为1到5.对于每个值,我需要更新具有相同目标位置的记录。

+1

为什么您需要多次执行相同的查询?在t-sql中有循环,但通常应该避免使用基于集合的解决方案。如果你可以发布你真正想做的事情的细节,我们可以帮助你找到一个不需要循环的解决方案。 –

+1

你想要的结果是什么?你是否想要每行四倍的结果集或者你想返回四个结果集? – Heinzi

+0

我不期待结果集,我正在更新一列数据 –

像一个简单的SQL WHILE循环?

declare @counter int 
set @counter = 0 

while @counter < 10 
begin 
select 'foo' 
set @counter = @counter + 1 
end 
+0

谢谢你。这工作。我不知道'while'在SQL中起作用。 :) –

认为你想在你的UPDATE联接,如:

--create two sample tables that we can work on 
declare @tabletoupdate table(ID int,TARGETLOCATION int); 
declare @sourcetable table(ID int,SOURCELOCATION int); 

--drop in sample data 
insert into @tabletoupdate select 1,10 union select 2,20 union select 3, 30; 
insert into @sourcetable select 1,100 union select 2,200 union select 3, 300; 

--see the 'before' 
select * from @tabletoupdate 
select * from @sourcetable 

--make target look like source 
update @tabletoupdate 
set 
    targetlocation = s.sourcelocation 
from 
    @tabletoupdate t 
    inner join @sourcetable s on s.id = t.id; 

--show 'after' 
select * from @tabletoupdate 
select * from @sourcetable 




/* 
--if you really insist on doing it with a loop 
--bad because its 
--1) slower 
--2) less readable 
--3) less reliable when other users are accessing the data 
declare @currentID int = 0; 
declare @maxID int = (select max(id) from @sourcetable); 
while @currentID < @maxID 
begin 
    set @currentID = @currentID + 1; 
    declare @newval int = (select sourcelocation 
    from @sourcetable 
    where id = @currentID 
    ); 
    if @newval is not null 
    begin 
    update @tabletoupdate 
    set TARGETLOCATION = @newval 
    where id = @currentID; 
    end 
end 
--*/ 

如果您正在运行在SQL Server Management Studio中的查询,那么你可以使用GO N到运行查询N次。例如:

insert into MyTable (MyCol) select 'NewRow' 
go 4 

这将在MyTable中插入4行,其中包含文本'NewRow'。

如果您确实需要在另一个应用程序中循环某些内容,那么我建议您使用Peter Tirrell建议的while循环。

请注意,在SQL中通常不需要循环。它们可能指示使用程序逻辑而不是基于集合的逻辑编写的代码。

+0

我从来没有见过这个,这是一个很酷的把戏! – JosephStyons