/****** Object:  StoredProcedure [dbo].[sp_ExportMedicalExaminationOfMinors]    Script Date: 19.10.2016 16:03:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_ExportMedicalExaminationOfMinors]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_ExportMedicalExaminationOfMinors]
GO
-----------------------------------------------------------
--kulak (c) 06.06.2015
--kulak@mz73.ru
--Выгрузка на портал МЗ РФ информации о диспансеризации детей
-----------------------------------------------------------
--Create PROCEDURE [sp_ExportMedicalExaminationOfMinors]
--	 @lpuID [uniqueidentifier]
--	,@xml [varchar](max) OUTPUT
--	,@errxml [varchar](max) OUTPUT
--	,@protokol [varchar](max) OUTPUT
--	,@dateFROM [datetime]
--	,@dateTO [datetime]
--	,@repeat [bit]
--	,@branchCode varchar(16) = null
--	--,@disptype [varchar](50) = null
--	,@CardNumber varchar(32) = null
--WITH EXECUTE AS CALLER
--AS
--BEGIN

--declare @xml_text [varchar](max);
--declare @cDate datetime;
--set @cDate = getdate();

--WITH EndPatient(PatientID, PolicyID,ContingentID,PatientJobID) 
--AS
--(
--	select 
--		pat.PatientID
--	,	(
--			select top 1 pol.PolicyID 
--			from AKUZ.T_POLICY pol with(nolock) 
--			where pol.type_ = 536 and pat.PatientID = pol.Patient 
--			order by pol.IssueDate desc, pol.ValidThrough asc
--		)
--	,	(
--			select top 1 ct.DispType
--			from AKUZ.T_PATIENT_CONTINGENT pc 
--			join AKUZ.T_CONTINGENT ct on ct.ContingentID = pc.Contingent
--			where pc.Patient = pat.PatientID and ct.DispType is not null
--		)
--	,	(
--			select top 1 pj.PatientJobID 
--			from AKUZ.T_PATIENT_JOB pj with(nolock) 
--			where pj.Patient = pat.PatientID and pj.JobType = 1 
--			order by pj.BeginDate desc, pj.EndDate asc
--		)
--	FROM AKUZ.T_PATIENT pat
--)

--select 
--	ac.patient as PatientID
--,	ac.AmbulanceCardID as AmbulanceCardID
--,	case	when ex_et.ExaminationType = 7 then '1' --сирота
--			else '3'  --несовершенолетний
--	end as idType
--,	ev_bs.EventID as EventID
--,	ep.PolicyID as PolicyID
--,	isnull(ep.ContingentID, '4') as ContingentID
--,	isnull(pj.Address, wp.Address) as PJadr
--,	isnull(pj.WorkPlace, isnull(wp.Name, wp.FullName)) as PJname
--,	wpb.DispType as PJidEducType
--,	rr.Code as PJcodeCity
--,	(
--		select top 1 mr.MedicalRecordID
--		from AKUZ.T_UNDERAGE_EXAMINATION rt
--		join AKUZ.T_MEDICAL_RECORD mr on mr.MedicalRecordID = rt.MedicalRecordID and mr.type_ = 1003 
--		join AKUZ.T_AMBULANCE_RECORD ar on ar.MedicalRecordID = mr.MedicalRecordID
--		where ar.AmbulanceEvent = ev_bs.EventID
--	) as UNDERAGE_EXAMINATION_ID
--,	(
--		select top 1 isnull(i.DispType, i_inog.DispType)
--		from AKUZ.T_POLICY pol
--		join AKUZ.T_INSURANCE_COMPANY ic on ic.OrganizationID = pol.InsuranceCompany
--		left join AKUZ.T_INSURER i on i.InsurerID = ic.Insurer
--		left join AKUZ.T_INSURER i_inog on i_inog.InsurerID = pol.Insurer
--		where pol.PolicyID = ep.PolicyID
--	) as ORPHInsurer
--,	(
--		SELECT top 1 vizzz.Post 
--		FROM AKUZ.T_VISIT vizzz 
--		join AKUZ.T_RESOURCE res on res.ResourceID = vizzz.Post
--		join AKUZ.T_SPECIALITY spec on spec.SpecialityID = res.Speciality
--		where vizzz.AmbulanceEvent = ev_bs.eventid and spec.DispType = 1 
--		order by vizzz.visitDate desc
--	) as ZaklPostID
--,	case	when ex_et.ExaminationType IN (8, 7) 
--				and exists 
--				(
--       	  			select 1 FROM AKUZ.T_VISIT t_basic1
--       	  			join AKUZ.T_V009_RESULT vp on vp.IDRMP = t_basic1.Rslt and vp.IDRMP in (321, 322, 323, 324, 325, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 347, 348, 349, 350, 351, 361, 362, 363, 364) --проф.осмотр;диспансеризация;медосмотр
--					--join AKUZ.T_VISIT_PURPOSE vp on vp.VisitPurposeID = t_basic1.VisitPurpose and vp.Code in (97, 98, 99) --проф.осмотр;диспансеризация;медосмотр
--       	  			where t_basic1.type_ IN (545,558,647,581,505) and t_basic1.AmbulanceEvent = ev_bs.eventid
--       	  		) 
--			then '2'
--       		when ex_et.ExaminationType IN (8, 7) 
--				and exists 
--				( 
--       	  			select 1 FROM AKUZ.T_VISIT t_basic1
--       	  			join AKUZ.T_VISIT_PURPOSE vp on vp.VisitPurposeID = t_basic1.VisitPurpose and vp.Code = 71	--профосмотр предварительный
--       	  			where  t_basic1.type_ IN (545,558,647,581,505) and t_basic1.AmbulanceEvent = ev_bs.eventid
--       			) 
--			then '3'
--       		when ex_et.ExaminationType IN (8, 7) 
--				and exists 
--				( 
--       	  			select 1 FROM AKUZ.T_VISIT t_basic1
--       	  			join AKUZ.T_VISIT_PURPOSE vp on vp.VisitPurposeID = t_basic1.VisitPurpose and vp.Code=  72	--профосмотр периодический
--       	  			where t_basic1.type_ IN (545,558,647,581,505) and t_basic1.AmbulanceEvent = ev_bs.eventid
--       	  		) 
--			then '4'
--	end as 'TypeOsmotr'
--into #orph_patients
--FROM AKUZ.T_EVENT_BASE ev_bs 
--LEFT JOIN AKUZ.T_EXAMINATION_BASE ex_bs on ex_bs.EventID = ev_bs.EventID
--LEFT JOIN AKUZ.T_EXAMINATION_TYPE ex_et on ex_et.ExaminationTypeID = ex_bs.ExaminationType
--LEFT JOIN AKUZ.T_AMBULANCE_CARD ac ON ac.AmbulanceCardID = ev_bs.AmbulanceCard 
--LEFT JOIN AKUZ.T_PATIENT pat ON pat.PatientID = ac.Patient
--JOIN EndPatient ep on ep.PatientID = pat.PatientID
--LEFT JOIN AKUZ.T_PATIENT_JOB pj on pj.PatientJobID = ep.PatientJobID
--LEFT JOIN AKUZ.T_WORKPLACE wp on wp.WorkplaceID = pj.WorkplaceDict
--LEFT JOIN AKUZ.T_ADDRESS addr on addr.Workplace = wp.WorkplaceID
--LEFT JOIN AKUZ.T_CITY cc on cc.CityID = addr.City
--left join AKUZ.T_RAJON rr on rr.RajonID = cc.Rajon
--LEFT JOIN AKUZ.T_WORKPLACE_BRANCH wpb on wpb.WorkplaceBranchID = wp.WorkplaceBranch
--LEFT JOIN AKUZ.T_USERS us on us.UserID = ev_bs.CreatorUser
--LEFT JOIN AKUZ.T_BRANCH br on br.LpuID = us.Branch
--where ac.cardlpu = @lpuID 
--and (@CardNumber = '' or @CardNumber is null or @CardNumber = ac.Number)
--and (ex_et.ExaminationType = 7 or ex_et.ExaminationType = 8)
----and 
----(
----	(@disptype is null or @disptype = '')
----	or 
----	(@disptype is not null and ex_bs.ExaminationType = cast(@disptype as varchar(50)))
----)

--and ev_bs.EventDate >= isnull(@dateFROM, '19500101') and ev_bs.EventDate < DATEADD(day, 1, isnull(@dateTO, GETDATE()))
--and ev_bs.CloseDate is not null
--and 
--(
--	@repeat = 1
--	or 
--	(not exists(select 1 from TX_DISP_EXISTS de where de.Event = ev_bs.EventID) and @repeat = 0)
--)
--and 
--(
--	(@branchCode is null or @branchCode = '')
--	or
--	br.BranchCode = @branchCode
--)
--and exists 
--(
--	select mr.MedicalRecordID
--	from AKUZ.T_UNDERAGE_EXAMINATION rt
--	join AKUZ.T_MEDICAL_RECORD mr on mr.MedicalRecordID = rt.MedicalRecordID and mr.type_ in (1003 ,1005)
--	join AKUZ.T_AMBULANCE_RECORD ar on ar.MedicalRecordID = mr.MedicalRecordID
--	where ar.AmbulanceEvent = ev_bs.EventID
--)

--delete part
--from #orph_patients part
--where isnull(part.TypeOsmotr, '0') in ('3', '4') --кроме профосмотр предварительный, профосмотр периодический - письмо в егисз от 19.08.16г

---------------
----build xml
---------------
--select @xml_text =
--(
--	select
--	(
--		Select
--			amc.AmbulanceCardID as 'idInternal'
--		,	part.idType as 'idType'
--		,	p.LastName 'name/last'
--		,	p.FirstName 'name/first'
--		,	isnull(p.FatherName, '') 'name/middle'
--		,	case when p.Sex = 10302 then '2' else '1' end 'idSex'
--		,	CONVERT(varchar(10), p.Birthday, 126) 'dateOfBirth'
--		,	part.ContingentID 'idCategory'
--		,	case 
--					when en.Alias in ('3', '14') then en.Alias 
--					when en.Alias = '24' then '3' 
--					when en.Alias in ('18', '4', '11', '12', '5', '1', '10', '9', '13', '15', '21', '22', '23', '25', '27', '28', '99') then '19' 
--					else '' end as 'idDocument'
--		,	isnull(replace(p.DocSeries, ' ', ''), '') as 'documentSer'
--		,	isnull(replace(p.DocNumber, ' ', ''), '') as 'documentNum'
--		,   case when replace(p.SNILS, ' ', '') <> '' then REPLACE (p.SNILS, ' ', '-') end as 'snils'
--		,	case when p.SNILS = '' then 3 end as 'without_snils_reason'
--		,	case when p.SNILS = '' then 'неизвестно' end as 'without_snils_other'
--		,	case when pol.PolicyForm > 1 then '2' else '1' end as 'idPolisType'
--		,	case when isnull(pol.Serial, '') = '' then '-' else pol.Serial end as 'polisSer'
--		,	isnull(pol.Number, 'нет') as 'polisNum'
--		,	isnull(part.ORPHInsurer, 37) as 'idInsuranceCompany'	-- --37	Москва	991D20D7-9F31-46F9-BEA3-E139AB296BF0
--		,	isnull(lpu.Name, '') as 'medSanName'
--		,	isnull(lpu.addressString, 'Мед учреждение без адреса') as 'medSanAddress'
		
--		--,	isnull(s.zipcode, c.ZipCode) as 'address/index' 
--		--,	isnull(c.code, '0000000000000') as 'address/kladrNP'
--		--,	s.code as 'address/kladrStreet'
--		--,	case when isnull(ar.House, '') = '' then null else ar.House end as 'address/house'
--		--,	case when isnull(ar.Block, '') = '' then null else ar.Block end as 'address/building'
--		--,	case when isnull(ar.Flat, '') = '' then null else ar.flat end as 'address/appartment'
--		,	left(lpset.RegionCode, 2) 'address/regionCode'
--		, '' as 'address/cityName' 
--		, '8bbaf531-2d1e-47fb-adb3-58b3edacd97c' as 'address/fiasAoid' 
----<!-- Место нахождения и образование -->
--		,	case when part.PJidEducType is not null and part.TypeOsmotr in ('3', '4') then part.PJcodeCity end as 'education/kladrDistr'
--		,	case when part.PJidEducType is not null and part.TypeOsmotr in ('3', '4') then part.PJidEducType end as 'education/idEducType' 
--		,	case when part.PJidEducType is not null and part.TypeOsmotr in ('3', '4') then isnull(part.PJname, 'Данные не указаны') end as 'education/educOrgName' --TODO
---- select 'idEducationOrg'  Данное поле игнорируется при указании поля education

--		,	case	when idType = 1 
--					then (
--							select top 1 case when un_ex.CurrentLocation = 5 then 8 else un_ex.CurrentLocation end 
--							FROM AKUZ.T_EXAMINATION_BASE ex_bs 
--							join AKUZ.T_EVENT_BASE ev_bs with(nolock) on ex_bs.EventID = ev_bs.EventID
--							join AKUZ.T_AMBULANCE_CARD ac with(nolock) on ac.AmbulanceCardID = ev_bs.AmbulanceCard
--							left join AKUZ.T_UNDERAGE_EXAMINATION un_ex with(nolock) on un_ex.MedicalRecordID = part.UNDERAGE_EXAMINATION_ID
--							where ev_bs.EventID = part.EventID
--						) 
--					else null 
--			end as 'idOrphHabitation'
--		,	case	when idType = 1 
--					then (
--							select top 1 CONVERT(varchar(10), un_ex.CurrentLocationDate, 126) 
--							FROM AKUZ.T_EXAMINATION_BASE ex_bs 
--							join AKUZ.T_EVENT_BASE ev_bs with(nolock) on ex_bs.EventID = ev_bs.EventID
--							join AKUZ.T_AMBULANCE_CARD ac with(nolock) on ac.AmbulanceCardID = ev_bs.AmbulanceCard
--							left join AKUZ.T_UNDERAGE_EXAMINATION un_ex with(nolock) on un_ex.MedicalRecordID = part.UNDERAGE_EXAMINATION_ID
--							where ev_bs.EventID = part.EventID
--						) 
--					else null 
--			end as 'dateOrphHabitation' 
----,case when idType = 1 then CONVERT(varchar(10), p.Birthday ,126) else null end as 'dateOrphHabitation' 
--		,case when (
--							select top 1 case when un_ex.CurrentLocation = 5 then 8 else un_ex.CurrentLocation end 
--							FROM AKUZ.T_EXAMINATION_BASE ex_bs 
--							join AKUZ.T_EVENT_BASE ev_bs with(nolock) on ex_bs.EventID = ev_bs.EventID
--							join AKUZ.T_AMBULANCE_CARD ac with(nolock) on ac.AmbulanceCardID = ev_bs.AmbulanceCard
--							left join AKUZ.T_UNDERAGE_EXAMINATION un_ex with(nolock) on un_ex.MedicalRecordID = part.UNDERAGE_EXAMINATION_ID
--							where ev_bs.EventID = part.EventID
--						) = 0 
--						then ( 
--								select top 1 w.Code
--								FROM AKUZ.T_PATIENT_JOB pj with(nolock) 
--								left join AKUZ.T_WORKPLACE w with(nolock) on w.WorkplaceID = pj.WorkplaceDict
--								where pj.Patient = part.PatientID
--								and pj.BeginDate <= @cDate
--								and (pj.EndDate >= @cDate or pj.EndDate is null)
--							) else null end as 'idStacOrg'	-- TODO ATTENTION!!! if idOrphHabitation=0 хз что ставить, тк привязки к справочнику нет никакой(

----cards//card
--		,	(
--				SELECT
--					ev_bs.eventid as 'idInternal'
--				,	CONVERT(varchar(10), ev_bs.eventDate, 126) as 'dateOfObsled'
--				,	isnull(un_ex.AgeByMonth, dbo.fnx_getFullMonth(p.Birthday, ev_bs.eventDate)) as 'ageObsled'
----,dbo.fnx_getFullMonth(p.Birthday,ev_bs.eventDate) as 'ageObsled'
--				,	case	when idType = 1 then '1'	 --сирота
----when idType = 3 and exists (
----							  select 1 FROM AKUZ.T_VISIT t_basic1 --JOIN AKUZ.T_POST t_basic4 ON t_basic4.ResourceID = t_basic1.Post
----							  join AKUZ.T_VISIT_PURPOSE vp on vp.VisitPurposeID = t_basic1.VisitPurpose and vp.Code in ('97','98', '99') --проф.осмотр;диспансеризация;медосмотр
----							  where t_basic1.type_ IN (545,558,647,581,505) and t_basic1.AmbulanceEvent = ev_bs.eventid
----						     ) then '2'
--							when idType = 3 and part.TypeOsmotr = '2' then '2'	--проф.осмотр;диспансеризация;медосмотр
----when idType = 3 and exists ( 
----							  select 1 FROM AKUZ.T_VISIT t_basic1 --JOIN AKUZ.T_POST t_basic4 ON t_basic4.ResourceID = t_basic1.Post 
----							  join AKUZ.T_VISIT_PURPOSE vp on vp.VisitPurposeID = t_basic1.VisitPurpose and vp.Code = '71'	--профосмотр предварительный
----							  where  t_basic1.type_ IN (545,558,647,581,505) and t_basic1.AmbulanceEvent = ev_bs.eventid
----					 ) then '3'
----when idType = 3 and exists ( 
----				              select 1 FROM AKUZ.T_VISIT t_basic1 --JOIN AKUZ.T_POST t_basic4 ON t_basic4.ResourceID = t_basic1.Post 
----				              join AKUZ.T_VISIT_PURPOSE vp on vp.VisitPurposeID = t_basic1.VisitPurpose and vp.Code=  '72'	--профосмотр периодический
----				              where t_basic1.type_ IN (545,558,647,581,505) and t_basic1.AmbulanceEvent = ev_bs.eventid
----					         ) then '4'
--       						else ''
--					end as 'idType'

----<!-- Развитие -->
--				,	isnull(un_ex.height, un_ex.height517) as 'height'
--				,	isnull(un_ex.mass, un_ex.mass517) as 'weight'
--				,	isnull(un_ex.HeadCircumference, 0) as 'headSize'
--				,	(
--						select problem 
--						from 
--						(
--							select un_ex.WeightDeviation + 1 as 'problem' 
--							union 
--							select un_ex.GrowthDeviation + 3 as 'problem'
--						) A 
--						where problem is not null 
--						FOR XML PATH(''), root('healthProblems'), type
--					)
		
--				,	case when dbo.fnx_getFullYears(p.birthday, ev_bs.eventdate) < 5 then isnull(un_ex.CognitiveFunction, 0) else 0 end as 'pshycDevelopment/poznav'
--				,	case when dbo.fnx_getFullYears(p.birthday, ev_bs.eventdate) < 5 then isnull(un_ex.MotoricFunction, 0) else 0 end as 'pshycDevelopment/motor'
--				,	case when dbo.fnx_getFullYears(p.birthday, ev_bs.eventdate) < 5 then isnull(un_ex.EmotionalSocialFunction, 0) else 0 end as 'pshycDevelopment/emot'
--				,	case when dbo.fnx_getFullYears(p.birthday, ev_bs.eventdate) < 5 then isnull(un_ex.PreSpeechAndSpeechGrowth, 0) else 0 end as 'pshycDevelopment/rech'
--				,	case when dbo.fnx_getFullYears(p.birthday, ev_bs.eventdate) > 4 then isnull(un_ex.PsychomotorGrowth, 0) else 0 end as 'pshycState/psihmot'
--				,	case when dbo.fnx_getFullYears(p.birthday, ev_bs.eventdate) > 4 then isnull(un_ex.Intellect, 0) else 0 end as 'pshycState/intel'
--				,	case when dbo.fnx_getFullYears(p.birthday, ev_bs.eventdate) > 4 then isnull(un_ex.EmotionalAndVegetativeSphereGrowth, 0) else 0 end as 'pshycState/emotveg'
--				,	case when dbo.fnx_getFullYears(p.birthday, ev_bs.eventdate) > 9 and p.Sex = 10301 then isnull(substring(un_ex.SexualFormulaBoy, 2, 1), '1') else null end as 'sexFormulaMale/P'
--				,	case when dbo.fnx_getFullYears(p.birthday, ev_bs.eventdate) > 9 and p.Sex = 10301 then isnull(substring(un_ex.SexualFormulaBoy, 6, 1), '1') else null end as 'sexFormulaMale/Ax'
--				,	case when dbo.fnx_getFullYears(p.birthday, ev_bs.eventdate) > 9 and p.Sex = 10301 then isnull(substring(un_ex.SexualFormulaBoy, 10, 1), '1') else null end as 'sexFormulaMale/Fa'
--				,	case when dbo.fnx_getFullYears(p.birthday, ev_bs.eventdate) > 9 and p.Sex = 10302 then isnull(substring(un_ex.SexualFormulaGirl, 2, 1), '1') else null end as 'sexFormulaFemale/P'
--				,	case when dbo.fnx_getFullYears(p.birthday, ev_bs.eventdate) > 9 and p.Sex = 10302 then isnull(substring(un_ex.SexualFormulaGirl, 6, 1), '1') else null end as 'sexFormulaFemale/Ma'
--				,	case when dbo.fnx_getFullYears(p.birthday, ev_bs.eventdate) > 9 and p.Sex = 10302 then isnull(substring(un_ex.SexualFormulaGirl, 10, 1), '1') else null end as 'sexFormulaFemale/Ax'
--				,	case when dbo.fnx_getFullYears(p.birthday, ev_bs.eventdate) > 9 and p.Sex = 10302 then isnull(substring(un_ex.SexualFormulaGirl, 14, 1), '1') else null end as 'sexFormulaFemale/Me'
--				,
--					(
--						select  
--							case when dbo.fnx_getFullYears(p.birthday, ev_bs.eventdate) > 9 and p.Sex = 10302 then isnull(un_ex.MenstrualFunction, 0) else 0 end as 'menarhe' 
--						,	(
--								select TT.char as 'char' 
--								from 
--								(
--									select isnull(un_ex.CharacteristicOfMenstrualFunction1, 0) + 1 as 'char'
--									union 
--									select	case 
--											 when un_ex.CharacteristicOfMenstrualFunction2 = 0 then 3
--											 when un_ex.CharacteristicOfMenstrualFunction2 = 1 then 5
--											 when un_ex.CharacteristicOfMenstrualFunction2 = 2 then 4
--											end --= -92 + (3851 x)/20 - (1123 x^2)/8 + (1117 x^3)/24 - (57 x^4)/8 + (49 x^5)/120
--										as 'char'
--									union 
--									select un_ex.CharacteristicOfMenstrualFunction3 + 6 as 'char'
--								) TT	
--								where TT.char is not null and dbo.fnx_getFullYears(p.birthday, ev_bs.eventdate) > 9 and p.Sex = 10302
--								FOR XML PATH(''), type
--							) as 'characters'
--						where dbo.fnx_getFullYears(p.birthday, ev_bs.eventdate) > 9 and p.Sex = 10302
--						FOR XML PATH('menses'), type
--					)

----<!-- Состояние здоровья до обследования -->
--				,	isnull(un_ex.healthGroup5 + 1, 1) as 'healthGroupBefore'
--				,	case when un_ex.PhysicalGroupBefore <> 4 then un_ex.PhysicalGroupBefore + 1 else -1 end as 'fizkultGroupBefore'

--				,	(
--						select 
--							left(ed.MKB,5) as 'mkb'
--						,	ed.DispensaryObservations + 1 as 'dispNablud'
--						,	(
--								select *
--								from 
--								(
--									select 
--										1 as 'Tag'
--									,	null as 'Parent'
--									,	isnull(ed.TreatmentPrescription, 0) + 1 as [lechen!1!condition!Element]
--									,	isnull(ed.TreatmentPlace, 0) + 1 as [lechen!1!organ!Element]
--									,	null as [notDone!2!reason!Element]
--									,	null as [notDone!2!reasonOther!Element]
--									union all
--									select 
--										2 as 'Tag'
--									,	1 as 'Parent'
--									,	null as [lechen!1!condition!Element]
--									,	null as [lechen!1!organ!Element]
--									,	case	when edd.AbortReasonPrescribedTreatment <> 5 then edd.AbortReasonPrescribedTreatment + 1 
--												when edd.AbortReasonPrescribedTreatment = 5 then 10
--												else null 
--										end as [notDone!2!reason!Element]
--									,	case when edd.AbortReasonPrescribedTreatment = 5 then isnull(edd.TretmentReasonDescription, 'незаполнено') end as [notDone!2!reasonOther!Element]
--								) temp_table
--								where ([Tag] = 1 and ([lechen!1!condition!Element] is not null or [lechen!1!organ!Element] is not null)) or ([Tag] = 2 and [notDone!2!reason!Element] is not null)
--								FOR XML EXPLICIT, type
--		  -- (SELECT
--				--ed.TreatmentPrescription+1 as 'condition',
--				--ed.TreatmentPlace+1 as 'organ', 
--				--(SELECT
--				--	case when edd.AbortReasonPrescribedTreatment<>5 then edd.AbortReasonPrescribedTreatment+1 
--				--		 when edd.AbortReasonPrescribedTreatment=5 then 10
--				--		 else null end as 'notDone/reason', 
--				--	case when edd.AbortReasonPrescribedTreatment=5 then edd.TretmentReasonDescription end as 'notDone/reasonOther'
--				--FOR XML PATH(''), type
--				--)
--			 --FOR XML PATH('lechen'), type
--							)
--						,	(
--								select *
--								from 
--								(
--									select 
--										1 as 'Tag'
--									,	null as 'Parent'
--									,	ed.PlaceOfReabilitation + 1 as [reabil!1!condition!Element]
--									,	ed.ReabilitationMade + 1 as [reabil!1!organ!Element]
--									,	null as [notDone!2!reason!Element]
--									,	null as [notDone!2!reasonOther!Element]
--									union all
--									select 
--										2 as 'Tag'
--									,	1 as 'Parent'
--									,	null as [reabil!1!condition!Element]
--									,	null as [reabil!1!organ!Element]
--									,	case	when edd.AbortReasonPrescribedReabilitation <> 5 then edd.AbortReasonPrescribedReabilitation + 1
--												when edd.AbortReasonPrescribedReabilitation = 5 then 10
--												else null 
--										end as [notDone!2!reason!Element]
--									,	case when edd.AbortReasonPrescribedReabilitation = 5 then isnull(edd.ReabilitationReasonDescription, 'незаполнено') end as [notDone!2!reasonOther!Element]
--								) temp_table
--								where ([Tag] = 1 and ([reabil!1!condition!Element] is not null or [reabil!1!organ!Element] is not null)) or ([Tag] = 2 and [notDone!2!reason!Element] is not null)
--								FOR XML EXPLICIT, type
--							)
--						,

--			--(SELECT
--			--	ed.PlaceOfReabilitation+1 as [reabil!condition!Element],
--			--	ed.ReabilitationMade+1 as [reabil!organ!Element], 
--			--	--(SELECT
--			--		case when edd.AbortReasonPrescribedReabilitation<>5 then edd.AbortReasonPrescribedReabilitation+1 
--			--			 when edd.AbortReasonPrescribedReabilitation=5 then 10
--			--			 else null end as [reabil!organ!notDone!reason!Element], 
--			--		case when edd.AbortReasonPrescribedReabilitation=5 then edd.ReabilitationReasonDescription end as [reabil!organ!notDone!reasonOther!Element]
--			--	--FOR XML PATH(''), type
--			--	--)
--			-- FOR XML EXPLICIT--PATH('reabil'), type--PATH(''), type, ROOT('reabil')
----			),

--							case when edd.HiTechTreatment > 0 then 1 when ed.HiTechRecomendation > 0 then 2 else 0 end as 'vmp'
--						from AKUZ.T_EXAMINATION_DIAGNOSIS_BEFORE edd
--						join AKUZ.T_EXAMINATION_DIAGNOSIS ed on ed.ExaminationDiagnosisID = edd.ExaminationDiagnosisID
--						where ed.UnderageExamination = un_ex.MedicalRecordID
--						FOR XML PATH('diagnosis'), root('diagnosisBefore'), type
--					)

----<!-- Состояние здоровья после обследования -->
--				,	case when un_ex.AfterMKB >= 'Z00' and un_ex.AfterMKB < 'Z11' then left(un_ex.AfterMKB, 5) end as 'healthyMKB'
--				,	(
--						select 
--							left(ed.MKB, 5) as 'mkb'
--						,	isnull(edd.FirstDiagnosis, 0) as 'firstTime'
--						,	case when ed.DispensaryObservations < 2 then ed.DispensaryObservations + 1 else 0 end as 'dispNablud'
--						,	ed.TreatmentPrescription + 1 as 'lechen/condition'
--						,	ed.TreatmentPlace + 1 as 'lechen/organ'
--						,	ed.PlaceOfReabilitation + 1 as 'reabil/condition'
--						,	ed.ReabilitationMade + 1 as 'reabil/organ'

--						,	edd.AdditionalConsultations + 1 as 'consul/condition'
--						,	edd.AdditionalConsultationsPlace + 1 as 'consul/organ'
--						,	edd.TypePerformAdditionalConsultations as 'consul/state'

--						,	isnull(ed.HiTechRecomendation, 0) as 'needVMP'
--						,	isnull(edd.AmbulanceRecommendation, 0) as 'needSMP'
--						,	isnull(edd.SpaTreatmentRecommendation, 0) as 'needSKL'
--						,	cast(isnull(un_ex.DespenseryRecomendations, '') as varchar(max)) + Char(10) + char(13) + isnull(lpu.Name, '') + Char(10) + char(13) + isnull(t_cards4.FIO, '') + '(' + isnull(v015sp.NAME, '') + ')' as 'recommendNext' --Рекомендации по диспансерному наблюдению, лечению, медицинской реабилитации и санаторно-курортному лечению с указанием вида медицинской организации и специальности врача
--						from AKUZ.T_EXAMINATION_DIAGNOSIS_AFTER edd
--						join AKUZ.T_EXAMINATION_DIAGNOSIS ed on ed.ExaminationDiagnosisID = edd.ExaminationDiagnosisID
--						where ed.UnderageExamination = un_ex.MedicalRecordID
--						FOR XML PATH('diagnosis'), root('diagnosisAfter'), type
--					)

----<!-- Инвалидность -->
--				,	( 
--						SELECT 
--							case 
--								when un_ex.Disabilities = 0 then '1'
--								when un_ex.Disabilities = 1 then '2'
--								when un_ex.Disabilities = 2 then '1'
--							end as 'invalid/type'
--						,	CONVERT(varchar(10), un_ex.DisabilitySetDate, 126) as 'invalid/dateFirstDetected'
--						,	CONVERT(varchar(10), un_ex.LastDisabilityGiven, 126) as 'invalid/dateLastConfirmed'
--						,	(select un_di.DisabilityDisease as 'illness' FROM AKUZ.T_UNDERAGE_DISABILITES un_di with(nolock) where un_ex.MedicalRecordID = un_di.UnderageExamination FOR XML PATH(''), type) as 'invalid/illnesses' 
--						,	(select split 'defect' from [fnx_GetDispChildXml_HealthInfringementType](HealthInfringementType) FOR XML PATH(''), type) as 'invalid/defects'
--						FOR XML PATH(''), TYPE
--					)

----<!-- Исследования -->
--				,	(
--						select 
--							(
--								select 
--									ms.DispType as 'id'
--								,	CONVERT(varchar(10), amcarrec.PostingDate, 126) as 'date'
--								,	isnull(ltrim(rtrim(cast(dires.ResultDescription as varchar(max)))), isnull(ltrim(rtrim(cast(dires.Decision as varchar(max)))), 'Результат не заполнен')) as 'result'
--								from AKUZ.T_DIAGNOSTICS_RESULTS dires with(nolock)
--								join AKUZ.T_AMBULANCE_CARD_RECORD amcarrec with(nolock) on amcarrec.MedicalRecordID = dires.MedicalRecordID
--								join AKUZ.T_MEDICAL_SERVICE ms with(nolock) on ms.MedicalServiceID = dires.Research
--								where amcarrec.AmbulanceEvent = ev_bs.EventID and ms.DispType is not null
--								order by ms.DispType
--								FOR XML PATH('record'), root('basic'), type
--							)
--						,	(
--								select 
--									CONVERT(varchar(10), amcarrec.PostingDate, 126) as 'date'
--								,	ms.Name as 'name'
--								,	isnull(ltrim(rtrim(cast(dires.ResultDescription as varchar(max)))), isnull(ltrim(rtrim(cast(dires.Decision as varchar(max)))), 'Результат не заполнен')) as 'result'
--								from AKUZ.T_DIAGNOSTICS_RESULTS dires with(nolock)
--								join AKUZ.T_AMBULANCE_CARD_RECORD amcarrec with(nolock) on amcarrec.MedicalRecordID = dires.MedicalRecordID
--								join AKUZ.T_MEDICAL_SERVICE ms with(nolock) on ms.MedicalServiceID = dires.Research
--								where amcarrec.AmbulanceEvent = ev_bs.EventID
--								and ms.DispType is null
--								order by amcarrec.PostingDate
--								FOR XML PATH('record'), root('other'), type
--							)
--						FOR XML PATH('issled'), type
--					)

----<!-- Заключение -->
--				,	un_ex.healthGroup + 1 as 'healthGroup'
--				,	case when un_ex.PhysicalGroupAfter <> 4 then un_ex.PhysicalGroupAfter + 1 else -1 end as 'fizkultGroup'
--				,	CONVERT(varchar(10), ev_bs.CloseDate, 126) as 'zakluchDate'
--				,	t_cards4.LastName as 'zakluchVrachName/last'
--				,	t_cards4.FirstName as 'zakluchVrachName/first'
--				,	t_cards4.FatherName as 'zakluchVrachName/middle'
--				,	(
--						SELECT
--							sp1.DispType as 'id' 
--						,	CONVERT(varchar(10), vizzz.visitDate, 126) as 'date'
--						FROM AKUZ.T_VISIT vizzz
--						JOIN AKUZ.T_POST post1 ON post1.ResourceID = vizzz.Post 
--						JOIN AKUZ.T_RESOURCE res1 ON res1.ResourceID = post1.ResourceID
--						join AKUZ.T_SPECIALITY sp1 on sp1.SpecialityID = res1.Speciality
--						where vizzz.type_ IN (545, 558, 647, 581, 505) 
--						and vizzz.AmbulanceEvent = ev_bs.eventid
--						and sp1.DispType is not null
--						order by vizzz.visitDate
--						FOR XML PATH('record'), type
--					) as 'osmotri'
--				,	isnull(un_ex.Recomendations, 'Соблюдение режима дня. Питание по возрасту. Прогулки на свежем воздухе. Соблюдение личной гигиены. Занятия физической культурой в соответствии с группой здоровья, закаливание, ЗОЖ') as 'recommendZOZH'

----<!-- Реабилитация -->
--				,	CONVERT(varchar(10), un_ex.IPR, 126) as 'reabilitation/date'
--				,	un_ex.IprExecutingState + 1 as 'reabilitation/state'

----<!-- Прививки -->
--				,	case 
--						when un_ex.PreventiveVactination < 3 then un_ex.PreventiveVactination + 1
--						when un_ex.PreventiveVactination = 3 then 5
--						when un_ex.PreventiveVactination > 3 then un_ex.PreventiveVactination 
--					end as 'privivki/state'
--				,	(select split as 'priv' from [fnx_GetDispChildXml_privivki](un_ex.Vactination) FOR XML PATH(''), type) as 'privivki/privs'

----<!-- Оплата ОМС -->
--				,	isnull
--					(
--						(
--							select top 1 case when isnull(sc.SUMP,0.) = 0. then '2' when sc.SUMP > 0. and sc.SUMP = sc.SUMV then '1' else '0' end
--							from AKUZ.T_SCHET_SLUCH sc 
--							where sc.[event] =  ev_bs.eventid
--						)
--						, '0'
--					) as 'oms'

--				FROM AKUZ.T_EXAMINATION_BASE ex_bs 
--				join AKUZ.T_EVENT_BASE ev_bs with(nolock) on ex_bs.EventID = ev_bs.EventID
--				join AKUZ.T_AMBULANCE_CARD ac with(nolock) on ac.AmbulanceCardID = ev_bs.AmbulanceCard
--				left join AKUZ.T_UNDERAGE_EXAMINATION un_ex with(nolock) on un_ex.MedicalRecordID = part.UNDERAGE_EXAMINATION_ID
--				--join AKUZ.T_MEDICAL_RECORD med_rec with(nolock) on med_rec.MedicalRecordID = part.UNDERAGE_EXAMINATION_ID
--				left JOIN AKUZ.T_POST t_cards2 with(nolock) ON t_cards2.ResourceID = part.ZaklPostID  
--				LEFT JOIN AKUZ.T_WORKER t_cards4 with(nolock) ON t_cards4.WorkerID = t_cards2.Worker
--				left join AKUZ.T_V015_SPECIALITY v015sp with(nolock) on v015sp.CODE = t_cards2.V015Speciality
--				where ev_bs.EventID = part.EventID
--				FOR XML PATH('card'), type
--			) as 'cards'
--		From AKUZ.T_PATIENT p with(nolock)
--		join #orph_patients part with(nolock) on p.PatientID = part.PatientID
--		Join AKUZ.T_PATIENT_ADDRESS ar with(nolock) On p.AddressReal = ar.AddressID
--		left join VCLib.T_ENUMS en with(nolock) on en.EnumID = p.DocType
--		Left Join AKUZ.T_STREET s with(nolock) On ar.Street = s.StreetID
--		Left Join AKUZ.T_CITY c with(nolock) On ar.City = c.CityID
--		Left Join AKUZ.T_RAJON r with(nolock) On c.Rajon = r.RajonID
--		Left Join AKUZ.T_REGION rg with(nolock) On c.Region = rg.RegionID
--		left Join AKUZ.T_POLICY pol with(nolock) On pol.PolicyID = part.PolicyID
--		left join AKUZ.T_AMBULANCE_CARD amc with(nolock) on amc.AmbulanceCardID = part.AmbulanceCardID
--		left join AKUZ.T_LPU_MAIN lpu with(nolock) on lpu.LpuID = amc.CardLpu
--		left join AKUZ.T_LPU_SETTINGS lpset on lpset.LpuMain = lpu.LpuID
--		ORDER BY p.Birthday, p.LastName, p.FirstName, p.FatherName 
--		FOR XML PATH('child'), ROOT('children')
--	) as xmltext
--)

----Проверка
----------------------
--select @xml_text = '<?xml version="1.0"?>' + @xml_text
--declare @tmp xml, @tmp1 xml
--select @tmp = convert(xml, @xml_text)

--if (@xml_text is not null)
--begin
--	EXECUTE [spx_ORPHxmlValidation] @tmp, @tmp1 OUTPUT
--end

--select @errxml = convert(varchar(max), @tmp1)

----Если ошибок нет, запоминаем выгруженные случаи
----------------------
--if (@errxml is null)
--begin
--	INSERT INTO [TX_DISP_EXISTS]([DispExistsID], [Event])
--    select newid(), ee.EventID
--	from #orph_patients ee
--	where not exists(select 1 from [TX_DISP_EXISTS] d where d.Event = ee.EventID)
--	group by ee.EventID
--end

--if exists(select top 1 EventID from #orph_patients) and @errxml is null
--begin
--	select @errxml = '<?xml version="1.0" encoding="UTF-8"?>'
--	+ (
--		select 
--			'Ошибок не обнаружено!' as 'FIO'
--		,	'-' as 'DR'
--		,	'-' as 'EventDate'
--		,	'-' as 'Document'
--		,	'-' as 'Error'
--		FOR XML PATH('zap'), ROOT('root')
--	)

----select @xml=CONVERT(varbinary(max),cast(@xml_text as nvarchar(max)),0)
--	select @xml = @xml_text
--end
--	--select @xml=@xml_text
--if not exists(select top 1 EventID from #orph_patients) and @errxml is null
--begin
--	select @errxml = '<?xml version="1.0" encoding="UTF-8"?>'
--	+ (
--		select 
--			'Не найдено записей для выгрузки!' as 'FIO'
--		,	'-' as 'DR'
--		,	'-' as 'EventDate'
--		,	'-' as 'Document'
--		,	'-' as 'Error'
--		FOR XML PATH('zap'), ROOT('root')
--	)
--end

----Протокол
----------------------
--if exists(select top 1 EventID from #orph_patients)
--begin
--	select @protokol = '<?xml version="1.0" encoding="UTF-8"?>'
--	+ (
--		select 
----			ROW_NUMBER() OVER (ORDER BY p.FIO ASC) AS 'Number',
--			p.FIO as 'FIO'
--		,	ac.Number as 'AmbCard'
--		,	CONVERT(varchar, p.Birthday, 104) as 'DR'
--		,	CONVERT(varchar, eb.EventDate, 104) as 'Date'
--		,	en.Name + '<br>' + isnull(p.DocSeries, '') + ' ' + isnull(p.DocNumber, '') as 'Document'
--		,	isnull(pol.Serial, '') + pol.Number + ' от ' + CONVERT(varchar, pol.IssueDate, 104) as 'Policy'
--		,	ROW_NUMBER() over (order by p.fio, p.Birthday, eb.EventDate) as 'RowNum'
--		from #orph_patients o
--		join AKUZ.T_EVENT_BASE eb on eb.EventID = o.EventID
--		join AKUZ.T_AMBULANCE_CARD ac on ac.AmbulanceCardID = eb.AmbulanceCard
--		join AKUZ.T_PATIENT p on p.PatientID = o.PatientID
--		left join AKUZ.T_POLICY pol on pol.PolicyID = o.PolicyID
--		left join VCLib.T_ENUMS en on en.EnumID = p.DocType
--		group by p.fio, p.Birthday, ac.Number, eb.EventDate, en.Name, p.DocSeries, p.DocNumber, pol.Serial, pol.Number, pol.IssueDate
--		--order by p.fio,p.Birthday,eb.EventDate
--		FOR XML PATH('zap'), ROOT('root')
--	)
--end
--else
--begin
--	select @protokol = '<?xml version="1.0" encoding="UTF-8"?>'
--	+ (
--		select 
----			'Не найдено записей для выгрузки!' as 'Number',
--			'Не найдено записей для выгрузки!' as 'FIO'
--		,	'-' as 'AmbCard'
--		,	'-' as 'DR'
--		,	'-' as 'Date'
--		,	'-' as 'Document'
--		,	'-' as 'Policy'
--		,	'-' as 'RowNum'
--		FOR XML PATH('zap'), ROOT('root')
--	)
--end

--drop table #orph_patients

--ExitLable:

--end





----@protokol
--<?xml version="1.0" encoding="utf-8"?>
--<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
--  <xsl:template match="/root">
--    <html>
--      <head>
--        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" lang="RU"/>
--        <title>Протокол выгрузки</title>
--        <style type="text/css">
--        </style>
--      </head>
--      <body>
--        <div>
--          <p align="center" style='margin-top:3.0pt;margin-right:0cm;margin-bottom:0cm;margin-left:0cm;margin-bottom:.0001pt;text-align:center'>
--            <b>ПРОТОКОЛ ВЫГРУЗКИ</b>
--          </p>
--          <br/>
--          <table border='1' cellspacing='0' cellpadding='0' align='center' style='border-collapse:collapse;border:none;'>
--            <tr style='height:20pt'>
--              <td width='50' valign='center'>
--                <p align='center' style='text-align:center;font-size:11.0pt'>
--                  <b>№ пп</b>
--                </p>
--              </td>
--              <td width='100' valign='center'>
--                <p align='center' style='text-align:center;font-size:11.0pt'>
--                  <b>№ карты</b>
--                </p>
--              </td>
--              <td width='396' valign='center'>
--                <p align='center' style='text-align:center;font-size:11.0pt'>
--                  <b>ФИО пациента</b>
--                </p>
--              </td>
--              <td width='150' valign='center'>
--                <p align='center' style='text-align:center;font-size:11.0pt'>
--                  <b>Дата рождения</b>
--                </p>
--              </td>
--              <td width='150' valign='center'>
--                <p align='center' style='text-align:center;font-size:11.0pt'>
--                  <b>Дата случая</b>
--                </p>
--              </td>
--			  <td width='396' valign='center'>
--                <p align='center' style='text-align:center;font-size:11.0pt'>
--                  <b>Документ</b>
--                </p>
--              </td>
--			  <td width='396' valign='center'>
--                <p align='center' style='text-align:center;font-size:11.0pt'>
--                  <b>Полис</b>
--                </p>
--              </td>
--            </tr>
--            <xsl:for-each select="zap">
--              <tr style='height:24.0pt'>
--                <td width='50' valign='center'>
--                  <p align='center' style='margin-right:10pt;margin-left:10pt;text-align:center;font-size:11.0pt'>
--                    <xsl:value-of select="RowNum" />
--                  </p>
--                </td>
--                <td width='100' valign='center'>
--                  <p align='center' style='margin-right:10pt;margin-left:10pt;text-align:center;font-size:11.0pt'>
--                    <xsl:value-of select="AmbCard" />
--                  </p>
--                </td>
--                <td width='396' valign='center'>
--                  <p align='center' style='margin-right:10pt;margin-left:10pt;text-align:center;font-size:11.0pt'>
--                    <xsl:value-of select="FIO" />
--                  </p>
--                </td>
--                <td width='150' valign='center'>
--                  <p align='center' style='text-align:center;font-size:11.0pt'>
--                    <xsl:value-of select="DR" />
--                  </p>
--                </td>
--                <td width='150' valign='center'>
--                  <p align='center' style='text-align:center;font-size:11.0pt'>
--                    <xsl:value-of select="Date" />
--                  </p>
--                </td>
--				<td width='396' valign='center'>
--                  <p align='center' style='text-align:center;font-size:11.0pt'>
--                    <xsl:value-of select="Document" disable-output-escaping="yes"/>
--                  </p>
--                </td>
--				<td width='396' valign='center'>
--                  <p align='center' style='text-align:center;font-size:11.0pt'>
--                    <xsl:value-of select="Policy" disable-output-escaping="yes"/>
--                  </p>
--                </td>
--              </tr>
--            </xsl:for-each>
--          </table>
--        </div>
--      </body>
--    </html>
--  </xsl:template>
--</xsl:stylesheet>



--------errxml
--<?xml version="1.0" encoding="utf-8"?>
--<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
--  <xsl:template match="/root">
--    <html>
--      <head>
--        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" lang="RU"/>
--        <title>Протокол выгрузки</title>
--        <style type="text/css">
--        </style>
--      </head>
--      <body>
--        <div>
--          <p align="center" style='margin-top:3.0pt;margin-right:0cm;margin-bottom:0cm;margin-left:0cm;margin-bottom:.0001pt;text-align:center'>
--            <b>ОШИБКИ</b>
--          </p>
--          <div>
--            <p align='right' style='margin:0cm;margin-bottom:.0001pt;text-align:right;border:none;padding:0cm;font-size:10.0pt'>
--              <b>Если у Вас ошибки не расшифрованы, сообщите об этом. <br/>Пожелания и замечания по телефону 38-41-94 доб 8 Александр<br/> Skype: al_kulakov</b>
--            </p>
--          </div>
--          <br/>
--          <table border='1' cellspacing='0' cellpadding='0' align='center' style='border-collapse:collapse;border:none;'>
--            <tr style='height:20pt'>
--              <td width='300' valign='center'>
--                <p align='center' style='text-align:center;font-size:11.0pt'>
--                  <b>ФИО пациента</b>
--                </p>
--              </td>
--              <td width='110' valign='center'>
--                <p align='center' style='text-align:center;font-size:11.0pt'>
--                  <b>Дата рождения</b>
--                </p>
--              </td>
--              <td width='120' valign='center'>
--                <p align='center' style='text-align:center;font-size:11.0pt'>
--                  <b>Документ</b>
--                </p>
--              </td>
--			  <td width='110' valign='center'>
--                <p align='center' style='text-align:center;font-size:11.0pt'>
--                  <b>Дата случая</b>
--                </p>
--              </td>
--              <td width='600' valign='center'>
--                <p align='center' style='text-align:center;font-size:11.0pt'>
--                  <b>Текст Ошибки</b>
--                </p>
--              </td>
--            </tr>
--            <xsl:for-each select="zap">
--              <tr style='height:24.0pt'>
--                <td width='300' valign='center'>
--                  <p align='center' style='margin-right:10pt;margin-left:10pt;text-align:center;font-size:11.0pt'>
--                    <xsl:value-of select="FIO" />
--                  </p>
--                </td>
--                <td width='110' valign='center'>
--                  <p align='center' style='text-align:center;font-size:11.0pt'>
--                    <xsl:value-of select="DR" />
--                  </p>
--                </td>
--                <td width='120' valign='center'>
--                  <p align='center' style='text-align:center;font-size:11.0pt'>
--                    <xsl:value-of select="Document" />
--                  </p>
--                </td>
--				<td width='110' valign='center'>
--                  <p align='center' style='text-align:center;font-size:11.0pt'>
--                    <xsl:value-of select="EventDate" />
--                  </p>
--                </td>
--			    <td width='600' valign='center'>
--                  <p align='center' style='text-align:center;font-size:11.0pt'>
--                    <xsl:value-of select="error" disable-output-escaping="yes"/>
--                  </p>
--                </td>
--              </tr>
--            </xsl:for-each>
--          </table>
--        </div>
--      </body>
--    </html>
--  </xsl:template>
--</xsl:stylesheet>