Create  PROCEDURE [dbo].[sp_Auto_Calc_Rows_Over]
	@DateName Varchar(25) , @stCondition Varchar(400) , @Code_Over_Under smallInt
AS
declare @stCommand    as varchar(2500)
if @Code_Over_Under <> -1 
 Set @stCondition = @stCondition + ' AND Over_Under_Factor_Drug.Code_Over_Under ='+CAST(@Code_Over_Under as varchar(5))

Set @stCommand = 
'Declare @AutoId int '+
'Declare @iRow_Index Int '+
'Declare @stUpdate_Year varchar(20) '+
'Set @iRow_Index = 1  '+
'Declare cur_List_Over Cursor '+
'For ' +
'SELECT  Over_Under_Factor_Drug.AutoId ' +
'FROM    Over_Under_Factor_Drug  '  +
'INNER JOIN  DrugH       ON Over_Under_Factor_Drug.Id_Havaleh      = DrugH.Id_Havaleh  '+
'LEFT  OUTER JOIN Doctor ON DrugH.Nezam_No                         = Doctor.Nezam_No   '+ 
'INNER JOIN  Over_Under  ON Over_Under_Factor_Drug.Code_Over_Under = Over_Under.AutoId '+ 
'INNER JOIN  Sahmiyeh    ON Sahmiyeh.Sazman_Code                   = DrugH.Sazman_Code '+
'Left Outer Join NoteBimeh On (NoteBimeh.Note_Code = DrugH.Note_Code and DrugH.Sazman_Code = NoteBimeh.Sazman_Code) '+
'Where DrugH.Kind_Flag = 1  AND  ISNULL(Over_Under_Factor_Drug.Over_Del_Flag , 1 ) = 1 '+ @stCondition + 
' Order By DrugH.' + @DateName + ', DrugH.Id_Havaleh '+
'Open cur_List_Over '+
'Fetch Next From cur_List_Over '+
'Into @AutoId  '+
'While @@FETCH_STATUS = 0  '+
'Begin '+
  'Exec dbo.sp_UpdateRow_Over  @AutoId , @iRow_Index '+
  'Set @iRow_Index = @iRow_Index + 1 '+
  'Fetch Next From cur_List_Over '+
  'Into @AutoId '+ 
'End '+
'Close cur_List_Over '+
'Deallocate  cur_List_Over '+
'print Cast(@iRow_Index-1  as varchar(4)) ' ;

Execute (@stCommand)
