迭代行sql server

时间:2015-09-07 08:34:21

标签: sql sql-server tsql sql-server-2012

我需要对所有具有相同ID的企业执行操作。我的ID从1到108。 我如何在sql server 2012中写这个?

到目前为止我试过了:

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个位置,然后我执行这个名为rate的列的计算。那部分我已经完成了,但我必须为这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 

- 现在我如何把我的选择放在这里,只有格式。只是直接写它们,包括括号或?

1 个答案:

答案 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中的数据不应该被删除,那么就没有机会犯错误并且排了两次,然后将该表中的所有内容复制到另一个temp中,使用第二个临时表执行上述操作。