SQL, How to loop for a date list using each as parameter for an Procedure? -


i have procedure receives specific date parameter ie exec procdb '20150428'

frequently need run procedure many dates , retype exec procdb 'date1' go exec procdb 'date2'go..... think it's not smart, so

i can valid list of dates using select distinct [dates] table1 order [dates].

so want create new procedure receives start_dt , end_dt , loops dates select distinct returns between including start_dt , end_dt.

ie like:  create procdblist start_dt date, end_dt date each date in: select distinct [date] [table1] [date] >= @start_dt , [date] <= @end_dt do: exec procdb 'date n' end 

updated:

final solution:

create procedure [dbo].[processdbrange] (@start_dt varchar(15) =null, @end_dt varchar(15) =null) begin declare @date varchar(15)  declare cursor_processdb cursor     select distinct convert(varchar(15), [date], 112) [date]     [prices]     [date] >= @start_dt , [date] <= @end_dt     order [date]  open cursor_processdb  fetch next cursor_processdb @date  while @@fetch_status = 0  begin  exec processdb @date  fetch next cursor_processdb @date  end close cursor_processdb deallocate cursor_processdb end 

this can accomplished using cursor.
basically, goes this:

declare @date datetime -- local variable cursor's result  declare datescursor cursor   select distinct [dates] [dates] between @start_dt , @end_dt table1 order [dates]. -- query cursor iterate on  open datescursor fetch next datescursor @date  while @@fetch_status = 0 -- 0 long cursor returns result   begin     exec procdb @date     fetch next datescursor @date -- don't forget fetch next result inside loop well!   end -- cleanup - important! close datescursor  deallocate datescursor  

edit
i've read link zimdanen gave in comments, must think in case may better using cursor.

edit #2

first, change open sub open cursor_name. second, use convert date string. make sure convert correct style, otherwise prone incorrect dates and/or exceptions.


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -