2015-09-07 81 views
-1

我需要對所有具有相同ID的輸入執行操作。我的ID從1到108. 我如何在sql server 2012中編寫這個?遍歷行sql server

到目前爲止,我嘗試:

select * 
into #ControlTable 
from myOriginalTable 

declare @ID int 
while exists (select * from #ControlTable) 
begin 
select top 1 @ID = ID 
from #ControlTable 
order by ID asc, name, date 

----code should go here, which is the syntax here, directly select * ... join on ...? 

或者我應該嘗試用光標? 東西的線路:

select * 
    into #ControlTable 
    from myOriginalTable 

DECLARE @theCursor CURSOR; 
DECLARE @ID int; 
begin 
    set @theCursor = CURSOR for 
    select * from #ControlTable 

    open @theCursor 
    fetch next from @theCursor 
    into @ID 

    WHERE @@fetch_status = 0 
begin 
-- again, not sure on how i need to write the syntax, i basically join two tables on a field 
into @id 
end; 

close @theCursor; 
deallocate @theCursor; 
END; 

編輯: 我想真正做什麼:基本上,我只創建一個indexNumber一個新的臨時表,這樣我就可以從原來的表連接數據到tempTable減去249個位置,然後我對這個稱爲速率的列進行計算。我已經完成了這部分,但是我必須爲這108個ID中的每一個都做到這一點。

EDIT2

the part of the code mentioned at my first edit contains those selects: 
select a, b, c, (index - 249) as indexNew 
into #temp1 
from originalTable 
order by some criteria 

然後我做 類似:

select t1.a, t1.b, t1.c, (t2.rate - t1.rate)* 100 as NewRate 
into #anotherTemp 
(
from 
    select * from #temp1 
) t1 
join 
(select * from #anotherTemp) t2 
on t1.index = t2.indexNew 

編輯3

EXPECTED result. 

    index col a  col b  col c id rate newRate 

    take the rate index go up 249 positions calculate newRate using the formula (t2.rate -t1.rate)*100 
, and do this for every id. 

    Once again, that part is working but only for one ID. I need to automate this. Thank you 

編輯4: 我真的需要這部分幫助: 後做:

declare @ID int 
while (select count (*) from #ControlTable) >0 
begin 
select top 1 @ID =ID from #ControlTable 

- 現在該怎麼辦,我把我的選擇,這使得該加盟這裏,不僅格式。直接寫下來,包括括號或?

+0

嗨Virel,你想獲得什麼,更明確。 Salut Viorel,ce vrei tu sa faci de fapt ?? Ai doua tabele si .. – CristiC777

+0

你想做什麼?請添加更多細節。 – DarkKnight

+0

這一切都取決於你在做什麼操作,你可能不需要逐行執行操作,並且最好避免這種操作,因爲這是非常低效的 –

回答

2
declare @ID int 
while (select count (*) from #ControlTable) >0 
begin 
select top 1 @ID =ID from #ControlTable 

(do something with your select here and when you are done) 

delete from #ControlTable where ID = @ID 
end 

這樣你會槽的所有行並沒有犯錯,並採取了一些連續兩次的機會,如果在#ControlTable的數據不應該被刪除,那麼一切事情,從表複製到另一個溫度,並用第二個臨時表執行上述操作。

+0

謝謝,我有一個想法,但不知道如何做到這一點。 –

+0

很高興幫助,這就是爲什麼我們都在這裏,我知道這種感覺。乾杯 – theweeknd