How can I output XML with different queries - sql

I am struggling at outputting XML the correct way. I'm trying to generate XML document with SQL Server query, which gives my the following:
CODE USED:
SELECT Plate, tbl_veiculos.ID, Brand, Model, Origin, Color
FROM tbl_veiculos, tbl_veiculo_spec
WHERE tbl_veiculos.ID = tbl_veiculo_spec.ID AND tbl_veiculos.ID = 1
FOR XML PATH ('Vehicle'), TYPE, ROOT('VehicleList')
RESULT:
<VehicleList>
<Vehicle>
<Plate>34-23-nd</Plate>
<ID>1</ID>
<Brand>Mercedes-Benz</Brand>
<Model>A140</Model>
<Origin>Germany</Origin>
<Color>Red</Color>
</Vehicle>
</VehicleList>
Which is to a certain way what I need. The problem comes when I try to merge it with other query output. I know this doesn't explain well so I'll show you an harcoded version of what I want.
<VehicleList>
<Vehicle>
<Plate>34-23-nd</Plate>
<ID>1</ID>
<Brand>Mercedes-Benz</Brand>
<Model>A140</Model>
<SellerInfo>
<Name>Someone Special</Name>
<Street>Oxfod Court 1231</Street>
</SellerInfo>
<Origin>Germany</Origin>
<Color>Red</Color>
</Vehicle>
</VehicleList>
<SellerInfo> comes from other table.

You can use subquery as below:
SELECT Plate, tbl_veiculos.ID, Brand, Model,
(select Name, Street from sellerInfo where id = t1.id --use id to join sellerInfo table
for xml Path(''), type) as SellerInfo,
Origin, Color,
FROM tbl_veiculos t1 inner join tbl_veiculo_spec ts
on tbl_veiculos.ID = tbl_veiculo_spec.ID AND tbl_veiculos.ID = 1
FOR XML PATH ('Vehicle'), TYPE, ROOT('VehicleList')

Related

Using TSQL and For XML Path to generate XML output

I have 3 temp tables all populated by 3 independent queries and are associated to each other with a 1 to 1 relationship, these tables are DemographicRecord, GPRegistrationDetails, MaternityBookingDetails. The columns are different between all 3 but each share the PatientID key. My question is using XML Path how can I output XML from the 3 related datasets following the format below.
<MAT001MothersDemographics>
<LocalPatientIdMother>BLANKED</LocalPatientIdMother>
<OrgCodeLocalPatientIdMother>BLANKED</OrgCodeLocalPatientIdMother>
<OrgCodeRes>BLANKED</OrgCodeRes>
<NHSNumberMother>BLANKED</NHSNumberMother>
<NHSNumberStatusMother>BLANKED</NHSNumberStatusMother>
<PersonBirthDateMother>BLANKED</PersonBirthDateMother>
<Postcode>BLANKED</Postcode>
<EthnicCategoryMother>BLANKED</EthnicCategoryMother>
<PersonDeathDateTimeMother>BLANKED</PersonDeathDateTimeMother>
<MAT003GPPracticeRegistration>
<LocalPatientIdMother>BLANKED</LocalPatientIdMother>
<OrgCodeGMPMother>BLANKED</OrgCodeGMPMother>
<StartDateGMPRegistration>BLANKED</StartDateGMPRegistration>
<EndDateGMPRegistration>BLANKED</EndDateGMPRegistration>
<OrgCodeCommissioner>BLANKED</OrgCodeCommissioner>
</MAT003GPPracticeRegistration>
<MAT101BookingAppointmentDetails>
<AntenatalAppDate>BLANKED</AntenatalAppDate>
<LocalPatientIdMother>BLANKED</LocalPatientIdMother>
<EDDAgreed>BLANKED</EDDAgreed>
<EDDMethodAgreed>BLANKED</EDDMethodAgreed>
<PregnancyFirstContactDate>BLANKED</PregnancyFirstContactDate>
<PregnancyFirstContactCareProfessionalType>BLANKED</PregnancyFirstContactCareProfessionalType>
<LastMenstrualPeriodDate>BLANKED</LastMenstrualPeriodDate>
<PhysicalDisabilityStatusIndMother>BLANKED</PhysicalDisabilityStatusIndMother>
<FirstLanguageEnglishIndMother>BLANKED</FirstLanguageEnglishIndMother>
<EmploymentStatusMother>BLANKED</EmploymentStatusMother>
<SupportStatusMother>BLANKED</SupportStatusMother>
<EmploymentStatusPartner>BLANKED</EmploymentStatusPartner>
<PreviousCaesareanSections>BLANKED</PreviousCaesareanSections>
<PreviousLiveBirths>BLANKED</PreviousLiveBirths>
<PreviousStillBirths>BLANKED</PreviousStillBirths>
<PreviousLossesLessThan24Weeks>BLANKED</PreviousLossesLessThan24Weeks>
<SubstanceUseStatus>BLANKED</SubstanceUseStatus>
<SmokingStatus>BLANKED</SmokingStatus>
<CigarettesPerDay>BLANKED</CigarettesPerDay>
<AlcoholUnitsPerWeek>BLANKED</AlcoholUnitsPerWeek>
<FolicAcidSupplement>BLANKED</FolicAcidSupplement>
<MHPredictionDetectionIndMother>BLANKED</MHPredictionDetectionIndMother>
<PersonWeight>BLANKED</PersonWeight>
<PersonHeight>BLANKED</PersonHeight>
<ComplexSocialFactorsInd>BLANKED</ComplexSocialFactorsInd>
</MAT101BookingAppointmentDetails>
</MAT001MothersDemographics>
So far I have tried:
SELECT
(SELECT * FROM #temp2
JOIN #temp ON #temp2.LocalPatientIdMother = #temp.LocalPatientIdMother
JOIN #temp3 ON #temp2.LocalPatientIdMother = #temp3.LocalPatientIdMother
FOR XML PATH('MAT001'), TYPE) AS 'MAT001MothersDemographics'
FOR XML PATH(''), ROOT('root')
But this is not the correct shape, can someone advise how I can use TSQL and FOR XML PATH effectively so I can generate the above output? I am currently getting the demographics repeated for every record before the other data is displayed?
<MAT001MothersDemographics>
<MAT001>
<LocalPatientIdMother>BLANKED</LocalPatientIdMother>
<OrgCodeLocalPatientIdMother>BLANKED</OrgCodeLocalPatientIdMother>
<OrgCodeRes>BLANKED</OrgCodeRes>
<NHSNumberMother>BLANKED</NHSNumberMother>
<NHSNumberStatusMother>BLANKED</NHSNumberStatusMother>
<PersonBirthDateMother>BLANKED</PersonBirthDateMother>
<Postcode>BLANKED</Postcode>
<EthnicCategoryMother>BLANKED</EthnicCategoryMother>
<PersonDeathDateTimeMother>BLANKED</PersonDeathDateTimeMother>
</MAT001>
</MAT001MothersDemographics>
<MAT001MothersDemographics>
<MAT001>
<LocalPatientIdMother>BLANKED</LocalPatientIdMother>
<OrgCodeLocalPatientIdMother>BLANKED</OrgCodeLocalPatientIdMother>
<OrgCodeRes>BLANKED</OrgCodeRes>
<NHSNumberMother>BLANKED</NHSNumberMother>
<NHSNumberStatusMother>BLANKED</NHSNumberStatusMother>
<PersonBirthDateMother>BLANKED</PersonBirthDateMother>
<Postcode>BLANKED</Postcode>
<EthnicCategoryMother>BLANKED</EthnicCategoryMother>
<PersonDeathDateTimeMother>BLANKED</PersonDeathDateTimeMother>
</MAT001>
</MAT001MothersDemographics>
Thanks very much
I must admit, that your question is quite unclear... You post a lot not needed details (e.g. big XMLs), but you do not provide the necessary information like table's structures and sample data. For the future please read How to ask a good SQL question and How to create a MCVE
But - my magic crystall ball is back from cleaning! - I try a quick shot:
SELECT t.*
,(
SELECT *
FROM #temp2 AS t2
WHERE t.LocalPatientIdMother=t2.LocalPatientIdMother
FOR XML PATH('MAT003GPPracticeRegistration'),TYPE
) AS [*]
,(
SELECT *
FROM #temp3 AS t3
WHERE t.LocalPatientIdMother=t3.LocalPatientIdMother
FOR XML PATH('MAT101BookingAppointmentDetail'),TYPE
) AS [*]
FROM #temp AS t
FOR XML PATH('MAT001MothersDemographics');
This will return all columns of #temp1 and will nest the related rows of #temp2 and #temp3. This is based on the assumption, that you have one record for the given ID in each table only...

How do I get SQL query with join and using STUFF and FOR XML PATH be sorted correctly

I have a master table that has one row per key and a detail table that has many rows per key with a sequence field that has a description field I need concatenated together and create one row per key. My code does this fine but the detail data row does not have the concatenated data in the correct order. The data is delivered to me in an Excel spreadsheet and I use the Import Wizard to add the data to the database. Since the order is not correct in the detail data I added a sub select to sort the data by key and sequence number that is the input into the STUFF WITH XML PATH. I am still getting the data in an incorrect order. If I sort the data in the spreadsheet first and then load it to the database it works fine. I really need this to work dynamically as I want to distribute this to my team and we can use it for different tables. Any ideas on why the sub select with the STUFF FOR XML PATH is not working? How can I do what I need?
Here is the code I have:
SELECT pic, pisc, piin
, STUFF((SELECT ' ' + P.PIIDTA FROM PI115AP P
Where P.PIC =B.PIC
and P.PISC = B.PISC
and P.PIIN = B.PIIN FOR XML PATH(''), type
).value('.', 'nvarchar(max)'),1,1,'') As CombinedDetail
From
( select TOP 100 PERCENT
pic, pisc, piin, piisn, piidta
from PI115AP
order by pic, pisc, piin, piisn) B
Group By B.PIC, B.pisc, B.piin
Thank you!
You have a lot of pieces and parts out of place for this to work the way you want it to. Your FOR XML is not in the order you want because the subquery has no order by. The actual result set is not in the order you want either because the main query does not have an order by. I don't really understand the point of the B subquery. The top does NOT order the actual results when using top, it just defines which rows to retrieve.
Pretty sure you want something more like this.
SELECT pic
, pisc
, piin
, STUFF((SELECT ' ' + P.PIIDTA
FROM PI115AP P
Where P.PIC = B.PIC
and P.PISC = B.PISC
and P.PIIN = B.PIIN
order by p.pic
, p.pisc
, p.piin
, p.piisn
FOR XML PATH(''), type
).value('.', 'nvarchar(max)'),1,1,'') As CombinedDetail
From PI115AP B
Group By B.PIC
, B.pisc
, B.piin
order by b.pic
, b.pisc
, b.piin

SQL to XML transfer of data

Ok have been trying to learn SQL to XML the last few days and this is what I have been able to teach my self thus far.
`SELECT distinct StudentItem.foldername AS "foldername", StudentItem.status, StudentItem.vhrid, StudentItem.firstname, StudentItem.middleinitial, StudentItem.lastname,
dbo.getEnumDescript(StudentType, 'StudentType') AS title,
StudentItem.email,
dbo.getEnumDescript(OfficeLocation, 'OfficeLocation') AS Office,
practices.id as 'StudentItem/practices/practice/id',
practices.name as 'StudentItem/practices/practice/name',
schoolItem.Name as 'StudentItem/bio/schools/schoolItem/schoolname',
schoolItem.schoolYear as 'lawyerItem/bio/schools/schoolItem/schoolyear'
FROM [dbo].[Student] as lawyerItem
LEFT JOIN [dbo].[StudentGroups] as aprac on StudentItem.vhrid = aprac.vhrid
INNER JOIN [dbo].[PracticeGroups] as practices on aprac.PracticeGroupID = practices.ID
LEFT JOIN [dbo].[StudentEducation] as schoolItem on StudentItem.vhrid = schoolItem.vhrid
where StudentItem.vhrid='50330'
FOR XML path, ROOT ('StudentItem'), ELEMENTS;`
What I get is this
`<StudentItems>
<row>
<foldername>susan.wissink</foldername>
<status>1</status>
<vhrid>50330</vhrid>
<firstname>Susan</firstname>
<middleinitial>M.</middleinitial>
<lastname>Wissink</lastname>
<title>Student leader</title>
<email>swissink#blank.com</email>
<Office>Phoenix</Office>
<StudentItem>
<practices>
<practice>
<id>681</id>
<name>Real Estate Finance and Lending</name>
</practice>
</practices>
<bio>
<schools>
<schoolItem>
<schoolname><i>Best in America®</i>, ASU</schoolname>
<schoolyear>2016</schoolyear>
</schoolItem>
</schools>
</bio>
</StudentItem>
</row>
<row>
<foldername>susan.wissink</foldername>
<status>1</status>
<vhrid>50330</vhrid>
<firstname>Susan</firstname>
<middleinitial>M.</middleinitial>
<lastname>Wissink</lastname>
<title>Student leader</title>
<email>swissink#blank.com</email>
<Office>Phoenix</Office>
<StudentItem>
<practices>
<practice>
<id>681</id>
<name>Real Estate Finance and Lending</name>
</practice>
</practices>
<bio>
<schools>
<schoolItem>
<schoolname><i>Best in America®</i>, UOP</schoolname>
<schoolyear>2011-2015</schoolyear>
</schoolItem>
</schools>
</bio>
</StudentItem>
</row>`
But I'm trying to get the all the practices and schools to show up as one entry for the guy that. More or less I'm trying to get it to look like below.
`<StudentItems>
<row>
<foldername>susan.wissink</foldername>
<status>1</status>
<vhrid>50330</vhrid>
<firstname>Susan</firstname>
<middleinitial>M.</middleinitial>
<lastname>Wissink</lastname>
<title>Student leader</title>
<email>swissink#blank.com</email>
<Office>Phoenix</Office>
<StudentItem>
<practices>
<practice>
<id>681</id>
<name>Real Estate Finance and Lending</name>
<id>683</id>
<name>Business and Finance</name>
</practice>
</practices>
<bio>
<schools>
<schoolItem>
<schoolname><i>Best in America®</i>, UOP</schoolname>
<schoolyear>2011-2015</schoolyear>
<schoolname><i>Best in America®</i>, ASU</schoolname>
<schoolyear>2016</schoolyear>
</schoolItem>
</schools>
</bio>
</StudentItem>
</row>`
Any help would be welcome. Thank You.
Without sample data, it's difficult to write code and test for. But generally what you need to do is to create sub-queries to create your practice and schoolItem XML nodes. Something like this:
SELECT distinct StudentItem.foldername AS "foldername",
StudentItem.status,
StudentItem.vhrid,
StudentItem.firstname,
StudentItem.middleinitial,
StudentItem.lastname,
dbo.getEnumDescript(StudentType, 'StudentType') AS title,
StudentItem.email,
dbo.getEnumDescript(OfficeLocation, 'OfficeLocation') AS Office,
(
select practices.id, practices.name
from [dbo].[StudentGroups] as aprac
INNER JOIN [dbo].[PracticeGroups] as practices
on aprac.PracticeGroupID = practices.ID
where StudentItem.vhrid = aprac.vhrid
FOR XML path(''), type
) 'StudentItem/practices/practice',
(
select Name schoolname, schoolYear
from [dbo].[StudentEducation] schoolItem
where StudentItem.vhrid = schoolItem.vhrid
FOR XML path(''), type
) 'StudentItem/bio/schools/schoolItem'
FROM [dbo].[Student] as StudentItem
where StudentItem.vhrid='50330'
FOR XML path, ROOT ('StudentItem');

TSQL inner select value in Outer Where Clause

I have a query that I slimmed down to a very basic example of what I am trying to do.
My issue is that I am creating a dynamic WHERE clause on my tool but can't even get the simple select below to work.
I have a table called BS_TrainingEvent_Segments that contains training events. An event can have multiple segments. My outer Where clause needs to be able to query both the Inner and Outer select but at the point it's at, it just says B cannot be bound.
SELECT A.[teSegmentID],
A.[trainingEventID],
A.[segmentDate],
A.[nonProdHrs],
(
SELECT B.[recordID],
B.[segmentID],
B.[localeID],
B.[teammateCount],
B.[leaderCount]
FROM dbo.BS_TrainingEvent_SegmentDetails AS B
WHERE A.teSegmentID = segmentID
FOR XML PATH ('detail'), TYPE, ELEMENTS, ROOT ('details')
) AS B
FROM [red].[dbo].[BS_TrainingEvent_Segments] AS A
WHERE A.[teCategory] = 'Food' AND B.[localeID] = '462'
FOR XML PATH ('data'), TYPE, ELEMENTS, ROOT ('root')
SELECT A.[teSegmentID],
A.[trainingEventID],
A.[segmentDate],
A.[nonProdHrs],
(
SELECT B.[recordID],
B.[segmentID],
B.[localeID],
B.[teammateCount],
B.[leaderCount]
FROM dbo.BS_TrainingEvent_SegmentDetails AS B
WHERE A.teSegmentID = B.segmentID AND B.[localeID] = '462'
FOR XML PATH ('detail'), TYPE, ELEMENTS, ROOT ('details')
)
FROM [red].[dbo].[BS_TrainingEvent_Segments] AS A
WHERE A.[teCategory] = 'Food'
FOR XML PATH ('data'), TYPE, ELEMENTS, ROOT ('root');

Getting data in appropriate format

I have a table which contains two column.
Agency Code MCI Numb
----------------------------
a 1234
a 12345
b 11
I need to write a query in SQl so that it will give data in following format.
< AgencyCode>
<ID>a</ID>
<MCI_NUMB>1234</MCI_NUMB>
<MCI_NUMB>12345</MCI_NUMB>
</AgencyCode>
< AgencyCode>
<ID>b</ID>
<MCI_NUMB>11</MCI_NUMB>
</AgencyCode>
You would need to use FOR XML / XPATH queries.
Try something like this:
SELECT ID
, CAST(MCI_Numb AS xml).query('/') AS MCI_Numbs
FROM(SELECT DISTINCT ID
, (SELECT MCI_Numb
FROM myTable
WHERE ID = T.ID
FOR XML PATH(''))AS MCI_Numb
FROM myTable AS T)AS T2
FOR XML PATH ('AgencyCode');
Take a look at this link: It explains in detail how to manipulate the sql server into xml and vice versa.
You probably need to take a look at :
FOR XML: http://technet.microsoft.com/en-us/library/ms177410(v=SQL.105).aspx
and
PIVOT: http://technet.microsoft.com/en-us/library/ms177410(v=SQL.105).aspx
The first will allow you to return xml, the second will allow you to pivot your data