2015-12-08 143 views
1

我有一個SQL查詢(正常的)。我必須連續運行這個查詢4次(就像編程中的For循環)。我怎麼能有一個像數組的東西,並重複查詢執行?不止一次像For循環一樣執行SQL語句

SQL服務器

更新:

我更新基於列TargetLocation一些數據。此目標位置的值爲1到5.對於每個值,我需要更新具有相同目標位置的記錄。

+1

爲什麼您需要多次執行相同的查詢?在t-sql中有循環,但通常應該避免使用基於集合的解決方案。如果你可以發佈你真正想做的事情的細節,我們可以幫助你找到一個不需要循環的解決方案。 –

+1

你想要的結果是什麼?你是否想要每行四倍的結果集或者你想返回四個結果集? – Heinzi

+0

我不期待結果集,我正在更新一列數據 –

回答

2

像一個簡單的SQL WHILE循環?

declare @counter int 
set @counter = 0 

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

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

2

認爲你想在你的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 
--*/ 
3

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

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

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

如果您確實需要在另一個應用程序中循環某些內容,那麼我建議您使用Peter Tirrell建議的while循環。

請注意,在SQL中通常不需要循環。它們可能指示使用程序邏輯而不是基於集合的邏輯編寫的代碼。

+0

我從來沒有見過這個,這是一個很酷的把戲! – JosephStyons