SQL to XML Output - sql

I was hoping I could get some help with this last part of a somewhat complicated problem I have been working on.
We have to produce an XML file from a SQL table that we are generating.
At its core the XML needs three elements.
Patient
PhoneAssessment
F2FAssessment
This is working as I'll show in my test code. However, the one problem we have is that if someone has both a F2FAssessment and a PhoneAssessment it will generate multiple tags.
If you all could give me some insight on the best way to fix this to where there will only be one Patient tag that contains all possible PhoneAssessment and F2FAssessment tags it would be greatly appreciated.
Here is the SQL code:
use tempdb;
declare #t table
(
[people_id] [nvarchar](255) NULL,
[actual_date] [date] NULL,
[NPI] [int] NULL,
[FileCreationDate] [date] NULL,
[FileCreationTime] [time](7) NULL,
[ProviderPatientNo] [int] NULL,
[LastName] [nvarchar](255) NULL,
[FirstName] [nvarchar](255) NULL,
[SSN] [nvarchar](255) NULL,
[DOB] [date] NULL,
[Gender] [int] NULL,
[Race] [int] NULL,
[Ethnicity] [int] NULL,
[ProviderPhoneAssessmentId] [nvarchar](255) NULL,
[CallEndDate] [date] NULL,
[CallEndTime] [time](7) NULL,
[DispatchDate] [date] NULL,
[DispatchTime] [time](7) NULL,
[CallDisposition] [int] NULL,
[DispositionOther] [nvarchar](255) NULL,
[Notes] [nvarchar](255) NULL,
[ProviderF2FAssessmentId] [nvarchar](255) NULL,
[AssessmentDate] [date] NULL,
[ArrivalTime] [time](7) NULL,
[ResidentialStatus] [int] NULL,
[County] [int] NULL,
[EmploymentStatus] [int] NULL,
[MaritalStatus] [int] NULL,
[MilitaryStatus] [int] NULL,
[NumArrests30Days] [nvarchar](255) NULL,
[AttendedSchoolLast3Months] [int] NULL,
[EducationLevel] [int] NULL,
[PrimaryPayorSource] [int] NULL,
[SecondaryPayorSource] [int] NULL,
[AnnualHouseholdIncome] [int] NULL,
[NumberInHousehold] [int] NULL,
[CurrentServices] [int] NULL,
[MHTreatmentDeclaration] [int] NULL,
[MOTStatus] [int] NULL,
[DurablePOA] [int] NULL,
[AssessmentLocation] [nvarchar](255) NULL,
[TransportedByLE] [int] NULL,
[TelevideoAssessment] [int] NULL,
[CurrentDetoxSymptoms] [int] NULL,
[HistoryOfDetoxSymptoms] [int] NULL,
[PrimaryDSMDiagnosis] [nvarchar](255) NULL,
[SecondaryDSMDiagnosis] [nvarchar](255) NULL,
[CompletedByLastName] [nvarchar](255) NULL,
[CompletedByFirstName] [nvarchar](255) NULL,
[DateDispositionCompleted] [date] NULL,
[TimeDispositionCompleted] [time](7) NULL,
[RecommendedTransportMode] [int] NULL,
[DateTransportedToFacility] [date] NULL,
[TimeTransportedToFacility] [time](7) NULL,
[FollowupContacted] [nvarchar](255) NULL,
[FollowupReportedServiceHelpful] [nvarchar](255) NULL,
[ContactAttempts] [nvarchar](255) NULL,
[VoluntaryAdmissionRecommended] [nvarchar](255) NULL,
[AdmissionAssessmentViaTelehealth] [nvarchar](255) NULL,
[IsAdmitted] [nvarchar](255) NULL,
[FirstHospitalization] [nvarchar](255) NULL,
[PrimaryProblem] [nvarchar](255) NULL,
[IntellectualDisability] [int] NULL,
[MedicalInstability] [int] NULL,
[MedicationIssues] [int] NULL,
[PastTrauma] [int] NULL,
[SubstanceAbuse] [int] NULL,
[Drug] [int] NULL,
[DrugRoute] [int] NULL,
[DrugFrequency] [int] NULL,
[HospAlternative] [nvarchar](255) NULL,
[HospAltDisposition] [nvarchar](255) NULL,
[Hospitalization] [nvarchar](255) NULL,
[HospitalizationDisposition] [nvarchar](255) NULL,
[SCS_Stf_Recommend] [nvarchar](255) NULL
)
insert INTO #t
([people_id],[actual_date],[NPI],[FileCreationDate],[FileCreationTime],[ProviderPatientNo],[LastName],[FirstName],[SSN],[DOB],[Gender],[Race],[Ethnicity],[ProviderPhoneAssessmentId],[CallEndDate],[CallEndTime],[DispatchDate],[DispatchTime],[CallDisposition],[DispositionOther],[Notes],[ProviderF2FAssessmentId],[AssessmentDate],[ArrivalTime],[ResidentialStatus],[County],[EmploymentStatus],[MaritalStatus],[MilitaryStatus],[NumArrests30Days],[AttendedSchoolLast3Months],[EducationLevel],[PrimaryPayorSource],[SecondaryPayorSource],[AnnualHouseholdIncome],[NumberInHousehold],[CurrentServices],[MHTreatmentDeclaration],[MOTStatus],[DurablePOA],[AssessmentLocation],[TransportedByLE],[TelevideoAssessment],[CurrentDetoxSymptoms],[HistoryOfDetoxSymptoms],[PrimaryDSMDiagnosis],[SecondaryDSMDiagnosis],[CompletedByLastName],[CompletedByFirstName],[DateDispositionCompleted],[TimeDispositionCompleted],[RecommendedTransportMode],[DateTransportedToFacility],[TimeTransportedToFacility],[FollowupContacted],[FollowupReportedServiceHelpful],[ContactAttempts],[VoluntaryAdmissionRecommended],[AdmissionAssessmentViaTelehealth],[IsAdmitted],[FirstHospitalization],[PrimaryProblem],[IntellectualDisability],[MedicalInstability],[MedicationIssues],[PastTrauma],[SubstanceAbuse],[Drug],[DrugRoute],[DrugFrequency],[HospAlternative],[HospAltDisposition],[Hospitalization],[HospitalizationDisposition],[SCS_Stf_Recommend])
VALUES
('90F07844-746A-4347-82CA-39D4332B43F3','2013-09-25','1306875695','2014-02-12','15:19:37.0000000','108677','David','Joe','414555555','1999-01-23','2','1','2','59DC25C9-B659-42A3-B43D-26C741F9B929','2013-09-26','15:17:00.0000000',NULL,NULL,'1',NULL,NULL,NULL,NULL,NULL,NULL,'87',NULL,'6','4',NULL,NULL,NULL,'9','9',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,'LastName','Alisha','2013-09-26','15:17:00.0000000',NULL,NULL,NULL,'0',NULL,NULL,NULL,NULL,'0',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL),
('90F07844-746A-4347-82CA-39D4332B43F3','2013-09-25','1306875695','2014-02-12','15:19:37.0000000','108677','David','Joe','414555555','1999-01-23','2','1','2',NULL,'2013-09-25','18:45:00.0000000','2013-09-25','18:51:00.0000000','4',NULL,NULL,'35159D47-32B2-445C-A905-019E191FDDE2','2013-09-25','19:22:00.0000000','13','47','12','6','4',NULL,'3','23','8','9','0','4','8','3','3','3','4','0','0','0','0','V71.09 ','V71.09','Tweed','A','2013-09-25','21:10:51.0000000','3',NULL,NULL,'1','1',NULL,'0','0','0',NULL,'2','3','3','3','3','2',NULL,NULL,NULL,'8','4',NULL,NULL,NULL)
IF OBJECT_ID('tempdb.dbo.#Patient') IS NOT NULL drop table #Patient
IF OBJECT_ID('tempdb.dbo.#Drugs') IS NOT NULL drop table #Drugs
IF OBJECT_ID('tempdb.dbo.#Assessments') IS NOT NULL drop table #Assessments
IF OBJECT_ID('tempdb.dbo.#HospAlt') IS NOT NULL drop table #HospAlt
IF OBJECT_ID('tempdb.dbo.#HospDisp') IS NOT NULL drop table #HospDisp
IF OBJECT_ID('tempdb.dbo.#PatientDistinct') IS NOT NULL drop table #PatientDistinct
--Patient Distinct
select distinct
ProviderPatientNo
into #PatientDistinct
FROM #t
--Patients
select distinct
NPI,
FileCreationDate,
FileCreationTime,
ProviderPatientNo,
ProviderF2FAssessmentId,
ProviderPhoneAssessmentId,
people_id, LastName,FirstName,
SSN,[DOB],[Gender],[Race],[Ethnicity]
into #Patient
FROM #t
--Assessments
SELECT
CallEndDate,
CallEndTime,
DispatchDate,
DispatchTime,
CallDisposition,
DispositionOther,
Notes,
people_id,
ProviderPatientNo,
ProviderF2FAssessmentId,
ProviderPhoneAssessmentId,
AssessmentDate,
case when ArrivalTime is null then '07:00:00' else ArrivalTime end AS [ArrivalTime] ,
ResidentialStatus AS [ResidentialStatus],
County AS [County],
EmploymentStatus AS [EmploymentStatus],
MaritalStatus AS [MaritalStatus],
MilitaryStatus AS [MilitaryStatus],
NumArrests30Days AS [NumArrests30Days],
AttendedSchoolLast3Months AS [AttendedSchoolLast3Months],
EducationLevel AS [EducationLevel],
PrimaryPayorSource AS [PrimaryPayorSource],
SecondaryPayorSource AS [SecondaryPayorSource],
AnnualHouseholdIncome AS [AnnualHouseholdIncome],
NumberInHousehold AS [NumberInHousehold],
CurrentServices AS [CurrentServices],
MHTreatmentDeclaration AS [MHTreatmentDeclaration],
MOTStatus AS [MOTStatus],
DurablePOA AS [DurablePOA],
AssessmentLocation AS [AssessmentLocation],
TransportedByLE AS [TransportedByLE],
TelevideoAssessment AS [TelevideoAssessment],
CurrentDetoxSymptoms AS [CurrentDetoxSymptoms],
HistoryOfDetoxSymptoms AS [HistoryOfDetoxSymptoms],
PrimaryDSMDiagnosis AS [PrimaryDSMDiagnosis],
SecondaryDSMDiagnosis AS [SecondaryDSMDiagnosis],
CompletedByLastName AS [CompletedByLastName],
CompletedByFirstName AS [CompletedByFirstName],
DateDispositionCompleted AS [DateDispositionCompleted],
TimeDispositionCompleted AS [TimeDispositionCompleted],
RecommendedTransportMode AS [RecommendedTransportMode],
DateTransportedToFacility AS [DateTransportedToFacility],
TimeTransportedToFacility AS [TimeTransportedToFacility],
FollowupContacted AS [FollowupContacted],
FollowupReportedServiceHelpful AS [FollowupReportedServiceHelpful],
ContactAttempts AS [ContactAttempts],
VoluntaryAdmissionRecommended AS [VoluntaryAdmissionRecommended],
AdmissionAssessmentViaTelehealth AS [AdmissionAssessmentViaTelehealth],
IsAdmitted AS [IsAdmitted],
FirstHospitalization AS [FirstHospitalization],
PrimaryProblem AS [PrimaryProblem],
IntellectualDisability AS [IntellectualDisability],
MedicalInstability AS [MedicalInstability],
MedicationIssues AS [MedicationIssues],
PastTrauma AS [PastTrauma],
SubstanceAbuse AS [SubstanceAbuse]
into #Assessments
FROM #t
--Drugs
select ProviderF2FAssessmentId,
Drug,
DrugRoute,
DrugFrequency
into #Drugs
from #t
where ProviderF2FAssessmentId is not null
--HospAlternative
select
ProviderF2FAssessmentId,
HospAlternative,
HospAltDisposition
into #HospAlt
from #t
where ProviderF2FAssessmentId is not null
--Hospitalization
select
ProviderF2FAssessmentId,
1 as Hospitalization,
10 as HospitalizationDisposition
into #HospDisp
from #t
where ProviderF2FAssessmentId is not null
/*Create XML*/
declare #output XML
set #output =
--Provider Data
(
SELECT
NPI as [NPI],
FileCreationDate as [FileCreationDate],
cast(FileCreationTime as time) FileCreationTime,
(
--Patient Data
Select
Patient.ProviderPatientNo ,
LastName as [LastName],
FirstName as [FirstName],
SSN as [SSN],
DOB as [DOB],
Gender as [Gender],
Race as [Race],
Ethnicity as [Ethnicity],
--Phone Assessment Data
/*
<ProviderPhoneAssessmentId>52854541</ProviderPhoneAssessmentId>
<CallEndDate>2006-05-04</CallEndDate>
<CallEndTime>01:01:01.001</CallEndTime>
<DispatchDate>2006-05-04</DispatchDate>
<DispatchTime>01:01:01.001</DispatchTime>
<CallDisposition>1</CallDisposition>
<DispositionOther>DispositionOther0</DispositionOther>
<Notes>Notes0</Notes>
*/
(
Select
ProviderPhoneAssessmentId,
CallEndDate,
CallEndTime,
DispatchDate,
DispatchTime,
CallDisposition,
DispositionOther,
Notes
FROM #Assessments
WHERE ProviderPhoneAssessmentId is NOT NULL and ProviderPhoneAssessmentId = Patient.ProviderPhoneAssessmentId
FOR XML PATH(''), ELEMENTS, type) AS [PhoneAssessment/*],
--F2FAssessment
/*
<ProviderF2FAssessmentId>4343</ProviderF2FAssessmentId>
<AssessmentDate>2006-05-04</AssessmentDate>
<ArrivalTime>01:01:01.001</ArrivalTime>
<ResidentialStatus>1</ResidentialStatus>
<County>1</County>
<EmploymentStatus>1</EmploymentStatus>
<MaritalStatus>1</MaritalStatus>
<MilitaryStatus>1</MilitaryStatus>
<NumArrests30Days>50</NumArrests30Days>
<AttendedSchoolLast3Months>1</AttendedSchoolLast3Months>
<EducationLevel>1</EducationLevel>
<PrimaryPayorSource>1</PrimaryPayorSource>
<SecondaryPayorSource>1</SecondaryPayorSource>
<AnnualHouseholdIncome>0</AnnualHouseholdIncome>
<NumberInHousehold>128</NumberInHousehold>
<CurrentServices>1</CurrentServices>
<MHTreatmentDeclaration>1</MHTreatmentDeclaration>
<MOTStatus>1</MOTStatus>
<DurablePOA>1</DurablePOA>
<AssessmentLocation>1</AssessmentLocation>
<TransportedByLE>false</TransportedByLE>
<TelevideoAssessment>false</TelevideoAssessment>
<CurrentDetoxSymptoms>false</CurrentDetoxSymptoms>
<HistoryOfDetoxSymptoms>false</HistoryOfDetoxSymptoms>
<PrimaryDSMDiagnosis>PrimaryDS</PrimaryDSMDiagnosis>
<SecondaryDSMDiagnosis>Secondary</SecondaryDSMDiagnosis>
<CompletedByLastName>CompletedByLastName2</CompletedByLastName>
<CompletedByFirstName>CompletedByFirstName2</CompletedByFirstName>
<DateDispositionCompleted>2006-05-04</DateDispositionCompleted>
<TimeDispositionCompleted>01:01:01.001</TimeDispositionCompleted>
<RecommendedTransportMode>1</RecommendedTransportMode>
<DateTransportedToFacility>2006-05-04</DateTransportedToFacility>
<TimeTransportedToFacility>01:01:01.001</TimeTransportedToFacility>
<FollowupContacted>false</FollowupContacted>
<FollowupReportedServiceHelpful>false</FollowupReportedServiceHelpful>
<ContactAttempts>128</ContactAttempts>
<VoluntaryAdmissionRecommended>false</VoluntaryAdmissionRecommended>
<AdmissionAssessmentViaTelehealth>false</AdmissionAssessmentViaTelehealth>
<IsAdmitted>false</IsAdmitted><FirstHospitalization>1</FirstHospitalization>
<PrimaryProblem>1</PrimaryProblem><IntellectualDisability>1</IntellectualDisability>
<MedicalInstability>1</MedicalInstability>
<MedicationIssues>1</MedicationIssues>
<PastTrauma>1</PastTrauma>
<SubstanceAbuse>1</SubstanceAbuse>
*/
(SELECT
ProviderF2FAssessmentId as [F2FAssessment/ProviderF2FAssessmentId],
AssessmentDate as [F2FAssessment/AssessmentDate],
[ArrivalTime] as [F2FAssessment/ArrivalTime],
ResidentialStatus as [F2FAssessment/ResidentialStatus],
County as [F2FAssessment/County],
EmploymentStatus AS [F2FAssessment/EmploymentStatus],
MaritalStatus AS [F2FAssessment/MaritalStatus],
MilitaryStatus AS [F2FAssessment/MilitaryStatus],
NumArrests30Days AS [F2FAssessment/NumArrests30Days],
AttendedSchoolLast3Months AS [F2FAssessment/AttendedSchoolLast3Months],
EducationLevel AS [F2FAssessment/EducationLevel],
PrimaryPayorSource AS [F2FAssessment/PrimaryPayorSource],
SecondaryPayorSource AS [F2FAssessment/SecondaryPayorSource],
AnnualHouseholdIncome AS [F2FAssessment/AnnualHouseholdIncome],
NumberInHousehold AS [F2FAssessment/NumberInHousehold],
CurrentServices AS [F2FAssessment/CurrentServices],
MHTreatmentDeclaration AS [F2FAssessment/MHTreatmentDeclaration],
MOTStatus AS [F2FAssessment/MOTStatus],
DurablePOA AS [F2FAssessment/DurablePOA],
AssessmentLocation AS [F2FAssessment/AssessmentLocation],
TransportedByLE AS [F2FAssessment/TransportedByLE],
TelevideoAssessment AS [F2FAssessment/TelevideoAssessment],
CurrentDetoxSymptoms AS [F2FAssessment/CurrentDetoxSymptoms],
HistoryOfDetoxSymptoms AS [F2FAssessment/HistoryOfDetoxSymptoms],
PrimaryDSMDiagnosis AS [F2FAssessment/PrimaryDSMDiagnosis],
SecondaryDSMDiagnosis AS [F2FAssessment/SecondaryDSMDiagnosis],
CompletedByLastName AS [F2FAssessment/CompletedByLastName],
CompletedByFirstName AS [F2FAssessment/CompletedByFirstName],
DateDispositionCompleted AS [F2FAssessment/DateDispositionCompleted],
TimeDispositionCompleted AS [F2FAssessment/TimeDispositionCompleted],
RecommendedTransportMode AS [F2FAssessment/RecommendedTransportMode],
ISNULL(CAST(DateTransportedToFacility as varchar(30)),'xsi:nil="true"') AS [F2FAssessment/DateTransportedToFacility],
ISNULL(CAST(TimeTransportedToFacility as varchar(30)),'xsi:nil="true"')AS [F2FAssessment/TimeTransportedToFacility],
FollowupContacted AS [F2FAssessment/FollowupContacted],
FollowupReportedServiceHelpful AS [F2FAssessment/FollowupReportedServiceHelpful],
ContactAttempts AS [F2FAssessment/ContactAttempts],
VoluntaryAdmissionRecommended AS [F2FAssessment/VoluntaryAdmissionRecommended],
AdmissionAssessmentViaTelehealth AS [F2FAssessment/AdmissionAssessmentViaTelehealth],
IsAdmitted AS [F2FAssessment/IsAdmitted],
FirstHospitalization AS [F2FAssessment/FirstHospitalization],
PrimaryProblem AS [F2FAssessment/PrimaryProblem],
IntellectualDisability AS [F2FAssessment/IntellectualDisability],
MedicalInstability AS [F2FAssessment/MedicalInstability],
MedicationIssues AS [F2FAssessment/MedicationIssues],
PastTrauma AS [F2FAssessment/PastTrauma],
SubstanceAbuse AS [F2FAssessment/SubstanceAbuse]
,
(
SELECT
ISNULL(Drug,'') as Drug,
DrugRoute,
DrugFrequency
From #Drugs drugs
Where drugs.Drug is NOT NULL and drugs.ProviderF2FAssessmentId = #Assessments.ProviderF2FAssessmentId
FOR XML PATH(''), type) AS [F2FAssessment/F2FDrug]
,
(
SELECT
HospAlternative,
HospAltDisposition
From #HospAlt HospAlt
Where HospAlt.ProviderF2FAssessmentId = #Assessments.ProviderF2FAssessmentId
FOR XML PATH(''), type) AS [F2FAssessment/F2FHospAlternative]
,
(
SELECT
Hospitalization,
HospitalizationDisposition
From #HospDisp HospDisp
Where HospDisp.ProviderF2FAssessmentId = #Assessments.ProviderF2FAssessmentId
FOR XML PATH(''), type) AS [F2FAssessment/F2FHospitalization]
FROM #Assessments
Where ProviderF2FAssessmentId IS NOT NULL and ProviderF2FAssessmentId = Patient.ProviderF2FAssessmentId
FOR XML PATH(''), ELEMENTS, type) AS [*]
FROM #Patient Patient
FOR XML PATH('Patient'), type
)
from #t
group by NPI,FileCreationDate, FileCreationTime
for xml path('')
)
; with xmlnamespaces ('http://www.tn.gov/mental/Schemas/CrisisAssessment' AS "xsd", 'http://www.w3.org/2001/XMLSchema-instance' as "xsi")
select #output FOR XML PATH(''),TYPE, ROOT('Provider')
Here is an example of the XML output that I am currently getting:
<Provider xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.tn.gov/mental/Schemas/CrisisAssessment">
<NPI>1306875695</NPI>
<FileCreationDate>2014-02-12</FileCreationDate>
<FileCreationTime>15:19:37</FileCreationTime>
<Patient>
<ProviderPatientNo>108677</ProviderPatientNo>
<LastName>David</LastName>
<FirstName>Joe</FirstName>
<SSN>414555555</SSN>
<DOB>1999-01-23</DOB>
<Gender>2</Gender>
<Race>1</Race>
<Ethnicity>2</Ethnicity>
<PhoneAssessment>
<ProviderPhoneAssessmentId>59DC25C9-B659-42A3-B43D-26C741F9B929</ProviderPhoneAssessmentId>
<CallEndDate>2013-09-26</CallEndDate>
<CallEndTime>15:17:00</CallEndTime>
<CallDisposition>1</CallDisposition>
</PhoneAssessment>
</Patient>
<Patient>
<ProviderPatientNo>108677</ProviderPatientNo>
<LastName>David</LastName>
<FirstName>Joe</FirstName>
<SSN>414555555</SSN>
<DOB>1999-01-23</DOB>
<Gender>2</Gender>
<Race>1</Race>
<Ethnicity>2</Ethnicity>
<F2FAssessment>
<ProviderF2FAssessmentId>35159D47-32B2-445C-A905-019E191FDDE2</ProviderF2FAssessmentId>
<AssessmentDate>2013-09-25</AssessmentDate>
<ArrivalTime>19:22:00</ArrivalTime>
<ResidentialStatus>13</ResidentialStatus>
<County>47</County>
<EmploymentStatus>12</EmploymentStatus>
<MaritalStatus>6</MaritalStatus>
<MilitaryStatus>4</MilitaryStatus>
<AttendedSchoolLast3Months>3</AttendedSchoolLast3Months>
<EducationLevel>23</EducationLevel>
<PrimaryPayorSource>8</PrimaryPayorSource>
<SecondaryPayorSource>9</SecondaryPayorSource>
<AnnualHouseholdIncome>0</AnnualHouseholdIncome>
<NumberInHousehold>4</NumberInHousehold>
<CurrentServices>8</CurrentServices>
<MHTreatmentDeclaration>3</MHTreatmentDeclaration>
<MOTStatus>3</MOTStatus>
<DurablePOA>3</DurablePOA>
<AssessmentLocation>4</AssessmentLocation>
<TransportedByLE>0</TransportedByLE>
<TelevideoAssessment>0</TelevideoAssessment>
<CurrentDetoxSymptoms>0</CurrentDetoxSymptoms>
<HistoryOfDetoxSymptoms>0</HistoryOfDetoxSymptoms>
<PrimaryDSMDiagnosis>V71.09 </PrimaryDSMDiagnosis>
<SecondaryDSMDiagnosis>V71.09</SecondaryDSMDiagnosis>
<CompletedByLastName>Tweed</CompletedByLastName>
<CompletedByFirstName>A</CompletedByFirstName>
<DateDispositionCompleted>2013-09-25</DateDispositionCompleted>
<TimeDispositionCompleted>21:10:51</TimeDispositionCompleted>
<RecommendedTransportMode>3</RecommendedTransportMode>
<DateTransportedToFacility>xsi:nil="true"</DateTransportedToFacility>
<TimeTransportedToFacility>xsi:nil="true"</TimeTransportedToFacility>
<FollowupContacted>1</FollowupContacted>
<FollowupReportedServiceHelpful>1</FollowupReportedServiceHelpful>
<VoluntaryAdmissionRecommended>0</VoluntaryAdmissionRecommended>
<AdmissionAssessmentViaTelehealth>0</AdmissionAssessmentViaTelehealth>
<IsAdmitted>0</IsAdmitted>
<PrimaryProblem>2</PrimaryProblem>
<IntellectualDisability>3</IntellectualDisability>
<MedicalInstability>3</MedicalInstability>
<MedicationIssues>3</MedicationIssues>
<PastTrauma>3</PastTrauma>
<SubstanceAbuse>2</SubstanceAbuse>
<F2FHospAlternative>
<HospAlternative>8</HospAlternative>
<HospAltDisposition>4</HospAltDisposition>
</F2FHospAlternative>
<F2FHospitalization>
<Hospitalization>1</Hospitalization>
<HospitalizationDisposition>10</HospitalizationDisposition>
</F2FHospitalization>
</F2FAssessment>
</Patient>
</Provider>
Here is an example of how I need it to look:
<Provider xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.tn.gov/mental/Schemas/CrisisAssessment">
<NPI>1306875695</NPI>
<FileCreationDate>2014-02-12</FileCreationDate>
<FileCreationTime>15:19:37</FileCreationTime>
<Patient>
<ProviderPatientNo>108677</ProviderPatientNo>
<LastName>David</LastName>
<FirstName>Joe</FirstName>
<SSN>414555555</SSN>
<DOB>1999-01-23</DOB>
<Gender>2</Gender>
<Race>1</Race>
<Ethnicity>2</Ethnicity>
<PhoneAssessment>
<ProviderPhoneAssessmentId>59DC25C9-B659-42A3-B43D-26C741F9B929</ProviderPhoneAssessmentId>
<CallEndDate>2013-09-26</CallEndDate>
<CallEndTime>15:17:00</CallEndTime>
<CallDisposition>1</CallDisposition>
</PhoneAssessment>
<F2FAssessment>
<ProviderF2FAssessmentId>35159D47-32B2-445C-A905-019E191FDDE2</ProviderF2FAssessmentId>
<AssessmentDate>2013-09-25</AssessmentDate>
<ArrivalTime>19:22:00</ArrivalTime>
<ResidentialStatus>13</ResidentialStatus>
<County>47</County>
<EmploymentStatus>12</EmploymentStatus>
<MaritalStatus>6</MaritalStatus>
<MilitaryStatus>4</MilitaryStatus>
<AttendedSchoolLast3Months>3</AttendedSchoolLast3Months>
<EducationLevel>23</EducationLevel>
<PrimaryPayorSource>8</PrimaryPayorSource>
<SecondaryPayorSource>9</SecondaryPayorSource>
<AnnualHouseholdIncome>0</AnnualHouseholdIncome>
<NumberInHousehold>4</NumberInHousehold>
<CurrentServices>8</CurrentServices>
<MHTreatmentDeclaration>3</MHTreatmentDeclaration>
<MOTStatus>3</MOTStatus>
<DurablePOA>3</DurablePOA>
<AssessmentLocation>4</AssessmentLocation>
<TransportedByLE>0</TransportedByLE>
<TelevideoAssessment>0</TelevideoAssessment>
<CurrentDetoxSymptoms>0</CurrentDetoxSymptoms>
<HistoryOfDetoxSymptoms>0</HistoryOfDetoxSymptoms>
<PrimaryDSMDiagnosis>V71.09 </PrimaryDSMDiagnosis>
<SecondaryDSMDiagnosis>V71.09</SecondaryDSMDiagnosis>
<CompletedByLastName>Tweed</CompletedByLastName>
<CompletedByFirstName>A</CompletedByFirstName>
<DateDispositionCompleted>2013-09-25</DateDispositionCompleted>
<TimeDispositionCompleted>21:10:51</TimeDispositionCompleted>
<RecommendedTransportMode>3</RecommendedTransportMode>
<DateTransportedToFacility>xsi:nil="true"</DateTransportedToFacility>
<TimeTransportedToFacility>xsi:nil="true"</TimeTransportedToFacility>
<FollowupContacted>1</FollowupContacted>
<FollowupReportedServiceHelpful>1</FollowupReportedServiceHelpful>
<VoluntaryAdmissionRecommended>0</VoluntaryAdmissionRecommended>
<AdmissionAssessmentViaTelehealth>0</AdmissionAssessmentViaTelehealth>
<IsAdmitted>0</IsAdmitted>
<PrimaryProblem>2</PrimaryProblem>
<IntellectualDisability>3</IntellectualDisability>
<MedicalInstability>3</MedicalInstability>
<MedicationIssues>3</MedicationIssues>
<PastTrauma>3</PastTrauma>
<SubstanceAbuse>2</SubstanceAbuse>
<F2FHospAlternative>
<HospAlternative>8</HospAlternative>
<HospAltDisposition>4</HospAltDisposition>
</F2FHospAlternative>
<F2FHospitalization>
<Hospitalization>1</Hospitalization>
<HospitalizationDisposition>10</HospitalizationDisposition>
</F2FHospitalization>
</F2FAssessment>
</Patient>
</Provider>
Any help you can offer would be greatly appreciated.

This is working as I'll show in my test code. However, the one problem we have is that if someone has both a F2FAssessment and a PhoneAssessment it will generate multiple tags.
This happen because you insert the person record 2 times.
first insert: Person data + phoneAssesment data
second insert: Peson data + F2FAssessment
Table t has 2 records for person with NPI:1306875695
my suggestion is to modify the #t table,
Create #temp1 table, the #temp1 should only have person data + phoneAssesment
Create #temp2 table, the #temp2 only contain PersonID + F2FAssessment (PErsonId act as foreign key)
Insert the data, to both table.
Inner Join both table #temp1 and #temp2 as Table #t. Use the PersonId as the join condition.
Now table #t will have only 1 record for NPI: 1306875695
Try this suggestion, Hope this is help.

If you only want one Patient element, make the PhoneAssessment and F2F* statements sub queries:
WITH XMLNAMESPACES (DEFAULT 'http://www.tn.gov/mental/Schemas/CrisisAssessment')
SELECT
[NPI],
[FileCreationDate],
[FileCreationTime],
(
SELECT
ProviderPatientNo,
LastName, FirstName,
SSN, DOB, Gender,
Race, Ethnicity,
(
SELECT
ProviderPhoneAssessmentId, CallEndDate, CallEndTime, CallDisposition
FROM #t pa
WHERE ProviderPhoneAssessmentId is not null
and pa.ProviderPatientNo = p.ProviderPatientNo
FOR XML PATH('PhoneAssesment'), TYPE, ELEMENTS XSINIL
),
(
SELECT
ProviderF2FAssessmentId,
AssessmentDate, ArrivalTime, ResidentialStatus, County, EmploymentStatus,
MaritalStatus, MilitaryStatus, AttendedSchoolLast3Months, EducationLevel,
PrimaryPayorSource, SecondaryPayorSource, AnnualHouseholdIncome,
NumberInHousehold, CurrentServices, MHTreatmentDeclaration, MOTStatus,
DurablePOA, AssessmentLocation, TransportedByLE, TelevideoAssessment,
CurrentDetoxSymptoms, HistoryOfDetoxSymptoms, PrimaryDSMDiagnosis,
SecondaryDSMDiagnosis, CompletedByLastName, CompletedByFirstName,
DateDispositionCompleted, TimeDispositionCompleted, RecommendedTransportMode,
DateTransportedToFacility, TimeTransportedToFacility, FollowupContacted,
FollowupReportedServiceHelpful, VoluntaryAdmissionRecommended,
AdmissionAssessmentViaTelehealth, IsAdmitted, PrimaryProblem,
IntellectualDisability, MedicalInstability, MedicationIssues, PastTrauma,
SubstanceAbuse,
HospAlternative as [F2FHospAlternative/HospAlternative],
HospAltDisposition as [F2FHospAlternative/HospAltDisposition],
Hospitalization as [F2FHospitalization/Hospitalization],
HospitalizationDisposition as [F2FHospitalization/HospitalizationDisposition]
FROM #t f2f
WHERE f2f.ProviderF2FAssessmentId is not null
and f2f.ProviderPatientNo = p.ProviderPatientNo
GROUP BY ProviderF2FAssessmentId,
AssessmentDate, ArrivalTime, ResidentialStatus, County, EmploymentStatus,
MaritalStatus, MilitaryStatus, AttendedSchoolLast3Months, EducationLevel,
PrimaryPayorSource, SecondaryPayorSource, AnnualHouseholdIncome,
NumberInHousehold, CurrentServices, MHTreatmentDeclaration, MOTStatus,
DurablePOA, AssessmentLocation, TransportedByLE, TelevideoAssessment,
CurrentDetoxSymptoms, HistoryOfDetoxSymptoms, PrimaryDSMDiagnosis,
SecondaryDSMDiagnosis, CompletedByLastName, CompletedByFirstName,
DateDispositionCompleted, TimeDispositionCompleted, RecommendedTransportMode,
DateTransportedToFacility, TimeTransportedToFacility, FollowupContacted,
FollowupReportedServiceHelpful, VoluntaryAdmissionRecommended,
AdmissionAssessmentViaTelehealth, IsAdmitted, PrimaryProblem,
IntellectualDisability, MedicalInstability, MedicationIssues, PastTrauma,
SubstanceAbuse, HospAlternative, HospAltDisposition, Hospitalization,
HospitalizationDisposition
FOR XML PATH('F2FAssessment'), TYPE, ELEMENTS XSINIL
)
FROM #t p
GROUP BY ProviderPatientNo, LastName, FirstName, SSN, DOB, Gender, Race, Ethnicity
FOR XML PATH('Patient'), TYPE, ELEMENTS XSINIL
)
FROM (SELECT TOP(1) [NPI], [FileCreationDate], [FileCreationTime] FROM #t) as FileHeader
FOR XML PATH('Provider'), ELEMENTS XSINIL
Also, I am guessing you want xsi:nil="true" to be an attribute. That is achieved through the XSINIL option. Also, you reference a namespace, but do not use it. Do you mean to make it the default (WITH XMLNAMESPACES (DEFAULT 'http://www.tn.gov/mental/Schemas/CrisisAssessment'))?
Produces:
<Provider xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.tn.gov/mental/Schemas/CrisisAssessment">
<NPI>1306875695</NPI>
<FileCreationDate>2014-02-12</FileCreationDate>
<FileCreationTime>15:19:37</FileCreationTime>
<Patient xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.tn.gov/mental/Schemas/CrisisAssessment">
<ProviderPatientNo>108677</ProviderPatientNo>
<LastName>David</LastName>
<FirstName>Joe</FirstName>
<SSN>414555555</SSN>
<DOB>1999-01-23</DOB>
<Gender>2</Gender>
<Race>1</Race>
<Ethnicity>2</Ethnicity>
<PhoneAssesment xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.tn.gov/mental/Schemas/CrisisAssessment">
<ProviderPhoneAssessmentId>59DC25C9-B659-42A3-B43D-26C741F9B929</ProviderPhoneAssessmentId>
<CallEndDate>2013-09-26</CallEndDate>
<CallEndTime>15:17:00</CallEndTime>
<CallDisposition>1</CallDisposition>
</PhoneAssesment>
<F2FAssessment xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.tn.gov/mental/Schemas/CrisisAssessment">
<ProviderF2FAssessmentId>35159D47-32B2-445C-A905-019E191FDDE2</ProviderF2FAssessmentId>
<AssessmentDate>2013-09-25</AssessmentDate>
<ArrivalTime>19:22:00</ArrivalTime>
<ResidentialStatus>13</ResidentialStatus>
<County>47</County>
<EmploymentStatus>12</EmploymentStatus>
<MaritalStatus>6</MaritalStatus>
<MilitaryStatus>4</MilitaryStatus>
<AttendedSchoolLast3Months>3</AttendedSchoolLast3Months>
<EducationLevel>23</EducationLevel>
<PrimaryPayorSource>8</PrimaryPayorSource>
<SecondaryPayorSource>9</SecondaryPayorSource>
<AnnualHouseholdIncome>0</AnnualHouseholdIncome>
<NumberInHousehold>4</NumberInHousehold>
<CurrentServices>8</CurrentServices>
<MHTreatmentDeclaration>3</MHTreatmentDeclaration>
<MOTStatus>3</MOTStatus>
<DurablePOA>3</DurablePOA>
<AssessmentLocation>4</AssessmentLocation>
<TransportedByLE>0</TransportedByLE>
<TelevideoAssessment>0</TelevideoAssessment>
<CurrentDetoxSymptoms>0</CurrentDetoxSymptoms>
<HistoryOfDetoxSymptoms>0</HistoryOfDetoxSymptoms>
<PrimaryDSMDiagnosis>V71.09 </PrimaryDSMDiagnosis>
<SecondaryDSMDiagnosis>V71.09</SecondaryDSMDiagnosis>
<CompletedByLastName>Tweed</CompletedByLastName>
<CompletedByFirstName>A</CompletedByFirstName>
<DateDispositionCompleted>2013-09-25</DateDispositionCompleted>
<TimeDispositionCompleted>21:10:51</TimeDispositionCompleted>
<RecommendedTransportMode>3</RecommendedTransportMode>
<DateTransportedToFacility xsi:nil="true" />
<TimeTransportedToFacility xsi:nil="true" />
<FollowupContacted>1</FollowupContacted>
<FollowupReportedServiceHelpful>1</FollowupReportedServiceHelpful>
<VoluntaryAdmissionRecommended>0</VoluntaryAdmissionRecommended>
<AdmissionAssessmentViaTelehealth>0</AdmissionAssessmentViaTelehealth>
<IsAdmitted>0</IsAdmitted>
<PrimaryProblem>2</PrimaryProblem>
<IntellectualDisability>3</IntellectualDisability>
<MedicalInstability>3</MedicalInstability>
<MedicationIssues>3</MedicationIssues>
<PastTrauma>3</PastTrauma>
<SubstanceAbuse>2</SubstanceAbuse>
<F2FHospAlternative>
<HospAlternative>8</HospAlternative>
<HospAltDisposition>4</HospAltDisposition>
</F2FHospAlternative>
<F2FHospitalization>
<Hospitalization xsi:nil="true" />
<HospitalizationDisposition xsi:nil="true" />
</F2FHospitalization>
</F2FAssessment>
</Patient>
</Provider>

Related

Stored procedure throws an error while getting data from two table using UNION

I have two tables which are shown in this screenshot:
I am writing a stored procedure which will return data from both tables:
ALTER PROCEDURE [dbo].[GetInventoryDetails]
#MaterialId INT
AS
BEGIN
SELECT
tms.Material_ID AS MaterialId,
tmm.Name As MaterialName,
CONVERT(varchar,Quantity) AS AddedQuantity,
UtilizedQuantity ='-',
tcl.LedgerName AS SupplierName,
UsedFor = '-',
tmm.CurrentStock,
tmm.OpeningStock,
CONVERT(DATETIME,CONVERT(VARCHAR(100), tms.Material_Date, 112)) AS MaterialDate,
tms.Narration AS Narration
FROM
tblMaterialSheet tms
JOIN
tblMaterialMaster tmm ON tmm.Material_ID = tms.Material_ID
JOIN
tblCompanyLedger tcl ON tcl.Pk_LedgerId = tms.Ledger_ID
WHERE
tms.Material_ID = #MaterialId
AND tms.isActive = 1
UNION
SELECT
tmu.Material_ID AS MaterialId,
tmm.Name As MaterialName,
AddedQuantity = '-',
CONVERT(varchar,Utilized_Quantity) AS UtilizedQuantity,
CONVERT(DATETIME,CONVERT(VARCHAR(100), Utilization_Date, 112)) AS MaterialDate,
SupplierName = '-',
tbst.Name AS UsedFor,
tmm.CurrentStock,
tmm.OpeningStock,
tmu.Narration As Narration
FROM
tblMaterialUtilization tmu
JOIN
tblMaterialMaster tmm ON tmm.Material_ID = tmu.Material_ID
JOIN
tblBuildingSubTask tbst ON tbst.BuildingSubTask_ID = tmu.BuildingSubTask_ID
WHERE
tmu.Material_ID = #MaterialId
AND tmu.isActive = 1
END
When I call the stored procedure, it throws an error:
Conversion failed when converting date and/or time from character string.
Table structure: tblmaterialsheet
CREATE TABLE [dbo].[tblMaterialSheet]
(
[MaterialSheet_ID] [int] IDENTITY(1,1) NOT NULL,
[Company_ID] [int] NOT NULL,
[User_ID] [int] NOT NULL,
[BuildingSubTask_ID] [int] NOT NULL,
[Material_Date] [datetime] NOT NULL,
[Material_ID] [int] NOT NULL,
[Unit_ID] [int] NOT NULL,
[Quantity] [decimal](10, 2) NOT NULL,
[Size_ID] [int] NULL,
[Height] [decimal](6, 2) NULL,
[Width] [decimal](6, 2) NULL,
[Rate_Per_Unit] [money] NULL,
[Paid_Amount] [money] NULL,
[Total_Amount] [money] NULL,
[Vehical_No] [varchar](50) NULL,
[Ledger_ID] [int] NULL,
[Narration] [varchar](max) NULL,
[Challan_No] [int] NULL,
[Bill_ID] [int] NULL,
[isBilled] [bit] NOT NULL,
[Approval] [varchar](50) NULL,
[Approval_ModifiedDate] [datetime] NULL,
[UploadImage] [image] NULL,
[isActive] [bit] NOT NULL,
[CreatedBy] [int] NOT NULL,
[CreatedDate] [datetime] NOT NULL,
[ModifiedBy] [int] NULL,
[ModifiedDate] [datetime] NULL
)
Table structure : tblMaterialUtilization
CREATE TABLE [dbo].[tblMaterialUtilization]
(
[MaterialUtilization_ID] [int] IDENTITY(1,1) NOT NULL,
[Company_ID] [int] NOT NULL,
[User_ID] [int] NOT NULL,
[BuildingSubTask_ID] [int] NOT NULL,
[Material_ID] [int] NOT NULL,
[Utilization_Date] [datetime] NOT NULL,
[Utilized_Quantity] [decimal](10, 2) NOT NULL,
[Narration] [varchar](max) NOT NULL,
[IsActive] [bit] NOT NULL,
[CreatedBy] [int] NOT NULL,
[CreatedDate] [datetime] NOT NULL,
[ModifiedBy] [int] NULL,
[ModifiedDate] [datetime] NULL
)
Table structure : tblMaterialMaster
CREATE TABLE [dbo].[tblMaterialMaster]
(
[Material_ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](100) NOT NULL,
[Unit_ID] [int] NOT NULL,
[IsActive] [bit] NOT NULL,
[CreatedBy] [int] NOT NULL,
[CreatedDate] [datetime] NOT NULL,
[ModifiedBy] [int] NULL,
[ModifiedDate] [datetime] NULL,
[OpeningStock] [numeric](18, 0) NULL,
[PurchaseLedger] [numeric](18, 0) NULL,
[CurrentStock] [numeric](18, 0) NULL
)
Table structure : tblBuildingSubTask
CREATE TABLE [dbo].[tblBuildingSubTask]
(
[BuildingSubTask_ID] [int] IDENTITY(1,1) NOT NULL,
[BuildingTask_ID] [int] NOT NULL,
[Name] [varchar](200) NOT NULL,
[Narration] [varchar](max) NULL,
[StartDate] [datetime] NULL,
[TargetCompletionDate] [datetime] NULL,
[ActualCompletionDate] [datetime] NULL,
[IsActive] [bit] NOT NULL,
[CreatedBy] [int] NOT NULL,
[CreatedDate] [datetime] NOT NULL,
[ModifiedBy] [int] NULL,
[ModifiedDate] [datetime] NULL
)
How to solve this error?
TRY THIS NOW: The order of the column were not in the same order so it was getting the different datatype values for the same column. Datatype and Order is most important in the UNION
ALTER PROCEDURE [dbo].[GetInventoryDetails]
#MaterialId int
AS
BEGIN
SELECT
tms.Material_ID AS MaterialId,
tmm.Name As MaterialName,
CONVERT(varchar,Quantity) AS AddedQuantity,
UtilizedQuantity ='-',
tcl.LedgerName AS SupplierName,
UsedFor='-',
tmm.CurrentStock,
tmm.OpeningStock,
CONVERT(DATETIME,CONVERT(VARCHAR(100), tms.Material_Date, 112)) AS MaterialDate,
tms.Narration As Narration
FROM
tblMaterialSheet tms
JOIN tblMaterialMaster tmm on tmm.Material_ID = tms.Material_ID
JOIN tblCompanyLedger tcl on tcl.Pk_LedgerId = tms.Ledger_ID
WHERE
tms.Material_ID = #MaterialId
AND
tms.isActive = 1
UNION
SELECT
tmu.Material_ID AS MaterialId,
tmm.Name As MaterialName,
AddedQuantity = '-',
CONVERT(varchar,Utilized_Quantity) AS UtilizedQuantity,
SupplierName = '-', --Moved up
tbst.Name AS UsedFor, --Moved up
tmm.CurrentStock, --Moved up
tmm.OpeningStock, --Moved up
CONVERT(DATETIME,CONVERT(VARCHAR(100), Utilization_Date, 112)) AS MaterialDate,
tmu.Narration As Narration
FROM
tblMaterialUtilization tmu
JOIN tblMaterialMaster tmm on tmm.Material_ID = tmu.Material_ID
JOIN tblBuildingSubTask tbst on tbst.BuildingSubTask_ID = tmu.BuildingSubTask_ID
WHERE
tmu.Material_ID = #MaterialId
AND
tmu.isActive = 1
END
The troubleshooting direction I'd take:
Look at your SQL. You're looking for anything that might be converting something of non-date type to date type. Your error probably means there's data somewhere you're converting to date that can't be converted. Be aware that this can include comparisons or functions that output a date.
Looking at your example, without knowing that actual data types, the only place I can see this happening is the explicit CONVERT functions on tms.Material_Date and Utilization_Date. I'd quickly comment these out and run each of the halves of the UNION separately. If they work, I could uncomment one or other until I figure out which field is causing the error. If they work independently but not unioned, I know that it's the after-union fields getting converted to date because the pre-union field is date.
Say it's the first half, before the union. I'd run:
SELECT * As Narration
FROM
tblMaterialSheet tms
JOIN tblMaterialMaster tmm on tmm.Material_ID = tms.Material_ID
JOIN tblCompanyLedger tcl on tcl.Pk_LedgerId = tms.Ledger_ID
WHERE
tms.Material_ID = #MaterialId
AND
tms.isActive = 1
AND
ISDATE(tms.Material_Date) = 0
You might need to work outwards in your converting to see where it falls over, e.g.,
AND
ISDATE(CONVERT(VARCHAR(100), tms.Material_Date, 112))
Then you should have a good idea about the problem.
Incidentally,
CONVERT(DATETIME,CONVERT(VARCHAR(100), Utilization_Date, 112))
looks very odd - what are you trying to achieve here by converting a date to varchar and back?
When you write a UNION or UNION ALL, You should make sure the following
No of Columns should be Same for Each Select Should Be same
Data Type of Column coming on the same position of each select Should be same
Suppose I have a column with character datatype for the first select and I'm trying to union it with a DateTime datatype, then I will get the error
SELECT 'ABCD'
UNION ALL
SELECT GETDATE()
This will throw the error
Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.
because the datatypes do not match.
And this will cause another error:
SELECT 'ABCD',GETDATE()
UNION ALL
SELECT GETDATE()
Like this:
Msg 205, Level 16, State 1, Line 1
All queries combined using a UNION, INTERSECT or EXCEPT operator must have an equal number of expressions in their target lists.
because the number of columns does not match.
So make sure that the datatypes match for each column in your UNION and if they does not match, try Cast or Convert

t-sql end of month insert

I have created two database tables named TSALESFACT and DimDate. TSALESFACT table contains the monthly sales target values. And DimTime contains the date values which begins from 01/01/2005.
CREATE TABLE [dbo].[TSalesFact](
[DateID] [smalldatetime] NULL,
[YearID] [int] NOT NULL,
[MonthID] [int] NOT NULL,
[SeasonID] [char](10) NOT NULL,
[DepartmentID] [char](10) NOT NULL,
[SalesAmount] [int] NOT NULL
)
CREATE TABLE [dbo].[dim_Date](
[ID] [int] NOT NULL,
[Date] [datetime] NOT NULL,
[Day] [char](2) NOT NULL,
[DaySuffix] [varchar](4) NOT NULL,
[DayOfWeek] [varchar](9) NOT NULL,
[DOWInMonth] [tinyint] NOT NULL,
[DayOfYear] [int] NOT NULL,
[WeekOfYear] [tinyint] NOT NULL,
[WeekOfMonth] [tinyint] NOT NULL,
[Month] [char](2) NOT NULL,
[MonthName] [varchar](9) NOT NULL,
[Quarter] [tinyint] NOT NULL,
[QuarterName] [varchar](6) NOT NULL,
[Year] [char](4) NOT NULL,
[StandardDate] [varchar](10) NULL,
[HolidayText] [varchar](50) NULL)
I would like to INSERT these sales target values into a new table named DailySalesTargets. But, the main purpose of this operation is writing the target sales to the each of end of month date. All of the date values for the relevant month will be zero. My desired resultset for this operation is like below:
How can I achieve this? Any idea?
I think this is what you are trying to do.
insert into [DailySalesTargets]([DateID],[YearID],[MonthID],
[SeasonID],[DepartmentID],[SalesAmount])
select d.[Date],d.[Year],d.[Month]
,dptSeason.[SeasonID],dptSeason.[DepartmentID]
,case when EOMONTH(d.[Date])=s.[DateID] then s.[SalesAmount] else 0 end as [SalesAmount]
from [dbo].[dim_Date] d
cross join (select distinct [DepartmentID],[SeasonID] from [dbo].[TSalesFact]) dptSeason
left join [dbo].[TSalesFact] s on d.[Date] = s.[DateID]
and s.[DepartmentID]=dptSeason.[DepartmentID]
and s.[SeasonID]=dptSeason.[SeasonID]

Trouble migrating data from old tables to a new one

I have two tables that I want to replace with a new one. The old tables:
CREATE TABLE [dbo].[OldContacts](
[OldContactID] [int] IDENTITY(1,1) NOT NULL,
[ClientID] [int] NULL,
[BusinessID] [int] NULL,
[Title] [varchar](20) NULL,
[FirstName] [varchar](100) NULL,
[Surname] [varchar](100) NULL,
[JobTitle] [varchar](100) NULL,
[EmailAddress] [varchar](100) NULL,
[Telephone] [varchar](20) NULL,
[Mobile] [varchar](20) NULL,
[DecisionMaker] [int] NULL,
[PrimaryContact] [int] NULL,
[ContactDisabled] [int] NULL,
[ZoomInfoPersonId] [int] NULL,
[CreationDate] [datetime] NULL,
[BusinessListRecordID] [int] NULL)
CREATE TABLE [dbo].[Transaction](
[TransactionId] [int] IDENTITY(1,1) NOT NULL,
[CreditTransactionId] [int] NOT NULL,
[PersonId] [int] NOT NULL,
[CompanyId] [int] NOT NULL,
[CompanyName] [nvarchar](150) NOT NULL,
[ContactName] [nvarchar](150) NOT NULL,
[ContactEmail] [nvarchar](150) NULL,
[ContactPhone] [nvarchar](50) NULL,
[ContactJobTitle] [nvarchar](150) NULL,
[EmailBought] [bit] NULL,
[AddressLine1] [varchar](100) NULL,
[AddressLine2] [varchar](100) NULL,
[AddressLine3] [varchar](100) NULL,
[County] [varchar](100) NULL,
[Town] [varchar](100) NULL,
[Country] [varchar](100) NULL,
[Telephone] [varchar](100) NULL,
[Website] [varchar](500) NULL,
[Industry] [varchar](100) NULL,
[BusinessID] [int] NULL)
And the new one:
CREATE TABLE [dbo].[ClientContacts](
[ClientContactID] [int] IDENTITY(1,1) NOT NULL,
[ClientUserID] [int] NULL,
[PersonID] [int] NULL,
[BusinessID] [int] NULL,
[CompanyID] [int] NULL,
[CompanyName] [varchar](50) NULL,
[ContactName] [varchar](100) NULL,
[ContactFirstName] [varchar](50) NULL,
[ContactSurname] [varchar](50) NULL,
[ContactEmail] [varchar](50) NULL,
[ContactPhone] [varchar](50) NULL,
[ContactMobile] [varchar](50) NULL,
[ContactJobTitle] [varchar](50) NULL,
[EmailBought] [bit] NULL,
[AddressLine1] [varchar](50) NULL,
[AddressLine2] [varchar](50) NULL,
[AddressLine3] [varchar](50) NULL,
[County] [varchar](50) NULL,
[Town] [varchar](50) NULL,
[Country] [varchar](50) NULL,
[CompanyTelephone] [varchar](50) NULL,
[CompanyWebsite] [varchar](50) NULL,
[Industry] [varchar](50) NULL,
[DecisionMaker] [bit] NULL,
[PrimaryContact] [bit] NULL,
[ContactDisabled] [bit] NULL,
[CreationDate] [datetime] NULL,
[BusinessListRecordID] [int] NULL,
[IsPurchased] [bit] NULL
)
The old logic was, you created a record on Transaction, and it would then add a record to OldContacts, creating the redundancy we are now trying to get rid of.
However, you could have a record on OldContacts that didn't come from a Transaction.
Now, I need to migrate the data to the new table, getting all the Transaction records plus the OldContacts that aren't duplicates of the Transaction ones. And here is what I've got so far:
INSERT INTO dbo.ClientContacts
(
ClientUserID, PersonID, BusinessID, CompanyID, CompanyName, ContactName,
ContactFirstName, ContactSurname, ContactEmail, ContactPhone, ContactMobile,
ContactJobTitle, EmailBought, AddressLine1, AddressLine2, AddressLine3,
County, Town, Country, CompanyTelephone, CompanyWebsite, Industry,
DecisionMaker, PrimaryContact, ContactDisabled, CreationDate,
BusinessListRecordID, IsPurchased
)
SELECT
CT.ClientUserId,
LC.ZIPersonId,
LC.BusinessID,
T.CompanyId,
T.CompanyName,
CONCAT(LC.FirstName, ' ', LC.Surname),
LC.FirstName,
LC.Surname,
LC.EmailAddress,
LC.Telephone AS ContactPhone,
LC.Mobile AS ContactMobile,
LC.JobTitle,
T.EmailBought,
T.AddressLine1,
T.AddressLine2,
T.AddressLine3,
T.County,
T.Town,
T.Country,
T.Telephone,
T.Website,
T.Industry,
LC.DecisionMaker,
LC.PrimaryContact,
LC.ContactDisabled,
LC.CreationDate,
LC.BusinessListRecordID,
CASE LC.ZIPersonId WHEN 0 THEN 0 ELSE 1 END
FROM OldContacts LC
LEFT OUTER JOIN dbo.[Transaction] T ON LC.ZIPersonId = T.PersonId
LEFT OUTER JOIN dbo.CreditTransaction CT ON T.CreditTransactionId = CT.CreditTransactionId
However, this only gets me one record, where the ZIPersonId matches. How can I get the records from both tables without getting duplicates?
Here are some test records:
INSERT INTO dbo.OldContacts (ClientID, BusinessID, Title, FirstName, Surname, JobTitle, EmailAddress, Telephone, Mobile, DecisionMaker, PrimaryContact, ContactDisabled, ZIPPersonId, CreationDate, BusinessListRecordID)
VALUES
(13832, 10, 'Mr', 'John55', 'Smith55', 'Admin', 'john55#smith.com', '123456', '123456', 0, 0, 0, 55, GETDATE(), NULL)
INSERT INTO dbo.OldContacts (ClientID, BusinessID, Title, FirstName, Surname, JobTitle, EmailAddress, Telephone, Mobile, DecisionMaker, PrimaryContact, ContactDisabled, ZIPPersonId, CreationDate, BusinessListRecordID)
VALUES
(13832, 10, 'Mr', 'John66', 'Smith66', 'Admin', 'john66#smith.com', '123456', '123456', 0, 0, 0, 66, GETDATE(), NULL)
INSERT INTO dbo.OldContacts (ClientID, BusinessID, Title, FirstName, Surname, JobTitle, EmailAddress, Telephone, Mobile, DecisionMaker, PrimaryContact, ContactDisabled, ZIPPersonId, CreationDate, BusinessListRecordID)
VALUES
(13832, 10, 'Mr', 'John77', 'Smith77', 'Admin', 'john77#smith.com', '123456', '123456', 0, 0, 0, 77, GETDATE(), NULL)
-- ******************************************************************************
INSERT INTO dbo.[Transaction] (CreditTransactionId, PersonId, CompanyId, CompanyName, ContactName, ContactEmail, ContactJobTitle, EmailBought, AddressLine1, AddressLine2, AddressLine3, County, Town, Country, Telephone, Website, Industry, BusinessID)
VALUES
(7965, 77, 123, 'TestCompany', 'John77 Smith77', 'john77#smith77.com', 'Admin', 1, 'AL1','AL2', 'AL3', 'testcounty', 'testtown', 'testcountry', '321456', 'www.test.com', 'someIndustry', 10)
EDIT
I replaced both joins with LEFT OUTER JOINS and I now have all the records. However, I am not getting some columns: no ClientUserId, CompanyId, CompanyName for contacts that come from the OldContacts table and the isPurchased field is always one, when it shouldn't, it should be 1 if the ZIPersonId is not 0.
It seems you have to replace the INNER JOIN with a LEFT JOIN:
INSERT INTO dbo.ClientContacts
(
ClientUserID, PersonID, BusinessID, CompanyID, CompanyName, ContactName,
ContactFirstName, ContactSurname, ContactEmail, ContactPhone, ContactMobile,
ContactJobTitle, EmailBought, AddressLine1, AddressLine2, AddressLine3,
County, Town, Country, CompanyTelephone, CompanyWebsite, Industry,
DecisionMaker, PrimaryContact, ContactDisabled, CreationDate,
BusinessListRecordID, IsPurchased
)
SELECT
CT.ClientUserId,
LC.ZIPersonId,
LC.BusinessID,
T.CompanyId,
T.CompanyName,
CONCAT(LC.FirstName, ' ', LC.Surname),
LC.FirstName,
LC.Surname,
LC.EmailAddress,
LC.Telephone AS ContactPhone,
LC.Mobile AS ContactMobile,
LC.JobTitle,
T.EmailBought,
T.AddressLine1,
T.AddressLine2,
T.AddressLine3,
T.County,
T.Town,
T.Country,
T.Telephone,
T.Website,
T.Industry,
LC.DecisionMaker,
LC.PrimaryContact,
LC.ContactDisabled,
LC.CreationDate,
LC.BusinessListRecordID,
CASE LC.ZIPersonId WHEN 0 THEN 0 ELSE 1 END
FROM OldContacts LC
LEFT JOIN dbo.[Transaction] T ON LC.ZIPersonId = T.PersonId
LEFT JOIN dbo.CreditTransaction CT ON T.CreditTransactionId = CT.CreditTransactionId
This will select the OldContacts even when there are no Transactions or CreditTransaction.
To answer your new question:
CASE LC.ZIPersonId WHEN 0 THEN 0 ELSE 1 END
Should be
CASE T.PersonId WHEN 0 THEN 0 ELSE 1 END
try an union first and then deselect all duplicates in the UNION of
OLDCONTACTS
and
TRANSACTION.
Its hard to replicate your case, I would try something like this:
select the-cols-you-need from
(
select a.the-cols-you-need, a.distinct(foreign-key) from
(
select * from oldcontacts
union all
select * from transaction
) as a
)
inner join CreditTransaction CT on a.transactionId = CT.transactionId

SQL fastest 'GROUP BY' script

Is there any difference in how I edit the GROUP BY command?
my code:
SELECT Number, Id
FROM Table
WHERE(....)
GROUP BY Id, Number
is it faster if i edit it like this:
SELECT Number, Id
FROM Table
WHERE(....)
GROUP BY Number , Id
it's better to use DISTINCT if you don't want to aggregate data. Otherwise, there is no difference between the two queries you provided, it'll produce the same query plan
This examples are equal.
DDL:
CREATE TABLE dbo.[WorkOut]
(
[WorkOutID] [bigint] IDENTITY(1,1) NOT NULL PRIMARY KEY,
[TimeSheetDate] [datetime] NOT NULL,
[DateOut] [datetime] NOT NULL,
[EmployeeID] [int] NOT NULL,
[IsMainWorkPlace] [bit] NOT NULL,
[DepartmentUID] [uniqueidentifier] NOT NULL,
[WorkPlaceUID] [uniqueidentifier] NULL,
[TeamUID] [uniqueidentifier] NULL,
[WorkShiftCD] [nvarchar](10) NULL,
[WorkHours] [real] NULL,
[AbsenceCode] [varchar](25) NULL,
[PaymentType] [char](2) NULL,
[CategoryID] [int] NULL
)
Query:
SELECT wo.WorkOutID, wo.TimeSheetDate
FROM dbo.WorkOut wo
GROUP BY wo.WorkOutID, wo.TimeSheetDate
SELECT DISTINCT wo.WorkOutID, wo.TimeSheetDate
FROM dbo.WorkOut wo
SELECT wo.DateOut, wo.EmployeeID
FROM dbo.WorkOut wo
GROUP BY wo.DateOut, wo.EmployeeID
SELECT DISTINCT wo.DateOut, wo.EmployeeID
FROM dbo.WorkOut wo
Execution plan:

How to create a calculated column in a SQL Server 2008 table

I really need a calculated column on a table with simple sum.
Please see below:
SELECT key3
,SUM(UTOTALWBUD)
FROM CONTACT1
INNER JOIN CONTACT2
ON CONTACT1.ACCOUNTNO = CONTACT2.ACCOUNTNO
WHERE KEY1 = 'Client'
GROUP BY KEY3
I have tried to create a calculated column by adding following
ALTER TABLE ManagerTaLog
ADD WeeklyBudget as ( SELECT
key3
,SUM(UTOTALWBUD)
FROM CONTACT1
JOIN CONTACT2
ON CONTACT1.ACCOUNTNO = CONTACT2.ACCOUNTNO
WHERE KEY1 = 'Client'
GROUP BY KEY3)
I got the error message:
Msg 1046, Level 15, State 1, Line 4
Subqueries are not allowed in this context. Only scalar expressions are allowed.
Please advise what can I do about it.
Many thanks
Part 2
I have create a function; however, i get null values please advise.
CREATE FUNCTION [dbo].[SumIt](#Key3 varchar)
RETURNS TABLE
AS
RETURN
(
SELECT SUM(UTOTALWBUD)
FROM CONTACT1
JOIN CONTACT2
ON CONTACT1.ACCOUNTNO = CONTACT2.ACCOUNTNO
JOIN Phone_List
ON CONTACT1.KEY3 = Phone_List.[Manager ]
WHERE KEY1 = 'Client'
AND Phone_List.[Manager ] = #Key3
GROUP BY [Manager ]
)
END
GO
Just select statment that returns values I wish to add to Phone_list table
SELECT [Manager ]
,SUM(UTOTALWBUD)
FROM CONTACT1
JOIN CONTACT2
ON CONTACT1.ACCOUNTNO = CONTACT2.ACCOUNTNO
JOIN Phone_List
ON CONTACT1.KEY3 = Phone_List.[Manager ]
WHERE KEY1 = 'Client'
GROUP BY [Manager ]
Table definitions
CREATE TABLE [dbo].[CONTACT1](
[ACCOUNTNO] [varchar](20) NOT NULL,
[COMPANY] [varchar](40) NULL,
[CONTACT] [varchar](40) NULL,
[LASTNAME] [varchar](15) NULL,
[DEPARTMENT] [varchar](35) NULL,
[TITLE] [varchar](35) NULL,
[SECR] [varchar](20) NULL,
[PHONE1] [varchar](25) NOT NULL,
[PHONE2] [varchar](25) NULL,
[PHONE3] [varchar](25) NULL,
[FAX] [varchar](25) NULL,
[EXT1] [varchar](6) NULL,
[EXT2] [varchar](6) NULL,
[EXT3] [varchar](6) NULL,
[EXT4] [varchar](6) NULL,
[ADDRESS1] [varchar](40) NULL,
[ADDRESS2] [varchar](40) NULL,
[ADDRESS3] [varchar](40) NULL,
[CITY] [varchar](30) NULL,
[STATE] [varchar](20) NULL,
[ZIP] [varchar](10) NOT NULL,
[COUNTRY] [varchar](20) NULL,
[DEAR] [varchar](20) NULL,
[SOURCE] [varchar](20) NULL,
[KEY1] [varchar](20) NULL,
[KEY2] [varchar](20) NULL,
[KEY3] [varchar](20) NULL,
[KEY4] [varchar](20) NULL,
[KEY5] [varchar](20) NULL,
[STATUS] [varchar](3) NOT NULL,
[NOTES] [text] NULL,
[MERGECODES] [varchar](20) NULL,
[CREATEBY] [varchar](8) NULL,
[CREATEON] [datetime] NULL,
[CREATEAT] [varchar](5) NULL,
[OWNER] [varchar](8) NOT NULL,
[LASTUSER] [varchar](8) NULL,
[LASTDATE] [datetime] NULL,
[LASTTIME] [varchar](5) NULL,
[U_COMPANY] [varchar](40) NOT NULL,
[U_CONTACT] [varchar](40) NOT NULL,
[U_LASTNAME] [varchar](15) NOT NULL,
[U_CITY] [varchar](30) NOT NULL,
[U_STATE] [varchar](20) NOT NULL,
[U_COUNTRY] [varchar](20) NOT NULL,
[U_KEY1] [varchar](20) NOT NULL,
[U_KEY2] [varchar](20) NOT NULL,
[U_KEY3] [varchar](20) NOT NULL,
[U_KEY4] [varchar](20) NOT NULL,
[U_KEY5] [varchar](20) NOT NULL,
[recid] [varchar](15) NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[Phone_List](
[Manager ] [nvarchar](255) NULL,
[SalesCode] [nvarchar](255) NULL,
[Email] [nvarchar](255) NULL,
[PayrollCode] [nvarchar](255) NULL,
[Mobile] [nvarchar](255) NULL,
[FName] [nchar](20) NULL,
[idd] [tinyint] NULL,
[OD] [varchar](20) NULL,
[WeeklyBudget] AS ([dbo].[SumIt]([manager]))
) ON [PRIMARY]
You can wrap your query into the function like this (it HAS to return one value):
CREATE FUNCTION dbo.SumIt(#Key1 varchar(max))
returns float
as
begin
return (select sum(UTOTALWBUD) from
CONTACT1 inner join
CONTACT2 on
CONTACT1.ACCOUNTNO=CONTACT2.ACCOUNTNO
where KEY1=#key1
group by KEY3)
END
And use this function instead with calc field - something like this:
alter table ManagerTaLog add WeeklyBudget as dbo.SumIt(Key1)
NOTE
that it will be the performance killer for queries like that:
select * from ManagerTaLog
You should change your function in such a way, that is accept NOT varchar value, but NVARCHAR(255) - the same type as Manager column. Try it.
If you resolve the issue of returning two values, one solution would be to implement the calculation in a function and use this function for the calculated column.
Some considerations
I have assumed that it is Key3 that needs to be passed to the function and have added a where clause to return the weekly budget for the given Key3 value.
The function will get executed for every record in a resultset where you add the calculated column.
Script
CREATE FUNCTION dbo.fn_ManagerTaLogWeeklyBudget(#Key3 INTEGER) RETURNS INTEGER AS
BEGIN
select sum(UTOTALWBUD) from
CONTACT1 inner join
CONTACT2 on
CONTACT1.ACCOUNTNO=CONTACT2.ACCOUNTNO
where KEY1='Client'
AND KEY3 = #Key3
group by KEY3)
END
GO
ALTER TABLE dbo.ManagerTaLog
ADD WeeklyBudget AS dbo.fn_ManagerTaLogWeeklyBudget(Key3)
You cannot have a subquery that returns multiple values to be used as the computed column expression.
You can have an expression that returns a single value - or you can wrap your code in a stored function - or you can create a view (with a JOIN or subquery) that combines this logic into something you can use
IMHO It is a wrong way. You have to use trigger on CONTACT tables and update WeeklyBudget in these triggers.
You can have calculated columns in a table but that will be present (and calculated) in all rows of the table.
The thing what you're trying to do in your select is called "aggregate". Try this:
select key3, sum(UTOTALWBUD) as WeeklyBudget from
CONTACT1 inner join CONTACT2 on CONTACT1.ACCOUNTNO=CONTACT2.ACCOUNTNO
where KEY1='Client'
group by key3
CREATE FUNCTION [dbo].[SumIt](#Key3 varchar)
RETURNS TABLE
AS
RETURN
(
SELECT SUM(ISNULL(UTOTALWBUD,0))
FROM CONTACT1
JOIN CONTACT2
ON CONTACT1.ACCOUNTNO = CONTACT2.ACCOUNTNO
JOIN Phone_List
ON CONTACT1.KEY3 = Phone_List.[Manager ]
WHERE KEY1 = 'Client'
AND Phone_List.[Manager ] = #Key3
GROUP BY [Manager ]
)
END
GO
Hope this will help. Please note that this is not a proper solution, but this may help your particular scenario. Since the function is returning multiple values, you can either user a table valued function or just modify the query in a way that it will return only one value. But if the column is nullable please don't forget to add ISNULL.