CREATE PROCEDURE spPatientsex 
    @ModalityType varchar(18), 
    @StatStartDttm datetime,
    @StatEndDttm datetime 
AS
BEGIN
 
DECLARE @iStudy_key int
DECLARE @sPatientsex varchar(2)
DECLARE @sBodyPart varchar(128)
DECLARE @iPos int
DECLARE @sBodyChild varchar(128)
DECLARE @iLen int


DECLARE crStudy CURSOR FOR

SELECT Study_key, patient_sex, study_bodypart
FROM study
WHERE study_modalitytype=@ModalityType  AND report_state > 0 AND
	study_dttm >= @StatStartDttm AND study_dttm <= @StatEndDttm 

OPEN crStudy

FETCH NEXT FROM crStudy 
INTO @iStudy_key,@sPatientsex,@sBodyPart

WHILE @@FETCH_STATUS = 0
BEGIN
  SET @sBodyPart=RTRIM(LTRIM(@sBodyPart))  
  IF LEN(@sBodyPart) > 0
  BEGIN
	  SET @iPos=CHARINDEX(' ',@sBodyPart)          
	  WHILE @iPos>=1       
	  BEGIN    
		SET @sBodyChild=SUBSTRING(@sBodyPart,1,@iPos-1)  
		INSERT INTO CC_Statist (Patient_sex,tmp_BodyPart,BodyPart_Weight)  
			VALUES(@sPatientsex,@sBodyChild,1)  
		SET @iLen=LEN(@sBodyPart)  
		SET @sBodyPart=SUBSTRING(@sBodyPart,@iPos+1,@iLen)  
		SET @sBodyPart=RTRIM(LTRIM(@sBodyPart))  
		SET @iPos=CHARINDEX(' ',@sBodyPart)  
	  END

	  INSERT INTO CC_Statist (study_key,Patient_sex,tmp_BodyPart,BodyPart_Weight)    
		VALUES(@iStudy_key,@sPatientsex,@sBodyPart,1) 
  END
  	
  FETCH NEXT FROM crStudy 
  INTO @iStudy_key,@sPatientsex,@sBodyPart  
END 

CLOSE crStudy     
DEALLOCATE crStudy 

END