Question : SQL - Stored Procedure Loop

Hi,

I'm using Miscrosoft SQL 2005.

I have a StoredProcedure. Each time I run this StoredProcedure  it takes a DateTime input:
exec MySP '2007-07-23'

...and creates a View
select ViewField from MyView

I have a query that returns me a list of DateTime fields
select MyDTField
from MyTable
order my MyDTField desc

2007-07-20 08:53:46.120
2007-07-21 00:00:00.000
2007-07-22 00:00:00.000

How can I loop throught all the datetime fields in MyTable query, and for each datetime value run the StoredProcedure MySP and insert the datetime value and the result from MyView in a table?

Code:
Foreach (datetime in MyTableQuery)
{
exec MySP 'datetime'      

select ViewField from MyView

insert into TmpTable(datetimeField, ViewField)
values('datetime', ViewField)
}

How is this possable in SQL?

Thank you.

Answer : SQL - Stored Procedure Loop

like this

declare @i int,@max int,@dt datetime

select MyDTField,identity(int,1,1) as rowid
  into #temp
from MyTable
order my MyDTField desc

select @i=1,@max=@@rowcount

create table #temp1 as (identity(int,1,1) as rowid
    ,mydtfield datetime,viewfield datetime)
   
while @i<=@max
begin
   select @dt=mydtfield,@i=@i+1
     from #temp
    where rowid=@i
   Insert into #temp1 (viewfield)
     exec mysp @dt
   Update #temp1
      set mydtfield=@dt
    Where mydtfield is null
end


   
Random Solutions  
 
programming4us programming4us