Reputation: 2528
Thanks to a fellow SO user I'm making progress with FOR XML, but I'm clearly not quite getting the sql syntax correct.
Let's say that I have the following sql
DECLARE @Uname VARCHAR(15) = 'Dom',
@Pword VARCHAR(15) = 'Monty'
SELECT
RTRIM(@Uname) AS '@uname',
RTRIM( @Pword) AS '@pword',
(SELECT COALESCE(PortOfLanding,'') AS portOfLanding
FROM Landings.LandingHeaders
WHERE Posted = 0
FOR XML PATH('Sale'))
FOR XML PATH('abc')
When run it produces the following as its output
<abc uname="Dom" pword="Monty"><Sale><portOfLanding>GBHTG</portOfLanding></Sale><Sale><portOfLanding>GBHTG</portOfLanding></Sale></abc>
What I was really hoping for though was the following
<abc uname="Dom" pword="Python">
<Sale portOfLanding= "GBHTG" />
<Sale portOfLanding= "GBHTG"/>
</abc>
and in fact I would like to add a third section to the SQL so that eventually one might end up with xml like so
<abc uname="Dom" pword="Python">
<Sale portOfLanding= "GBHTG">
<saleline detail="some value here" />
<saleline detail="some value here" />
<Sale/>
<Salesnote portOfLanding= "GBHTG"/>
</abc>
Can someone point out where I've gone wrong in the original SQL query?
Thanks
Upvotes: 0
Views: 70
Reputation: 35780
Try this:
DECLARE @Uname VARCHAR(15) = 'Dom',
@Pword VARCHAR(15) = 'Monty';
SELECT RTRIM(@Uname) AS '@uname',
RTRIM( @Pword) AS '@pword',
(SELECT COALESCE(PortOfLanding,'') AS '@portOfLanding'
FROM Landings.LandingHeaders
WHERE Posted = 0
FOR XML PATH('Sale'), TYPE)
FOR XML PATH('abc')
You can go deeper like:
SELECT RTRIM(@Uname) AS '@uname',
RTRIM( @Pword) AS '@pword',
(SELECT COALESCE(PortOfLanding,'') AS '@portOfLanding',
(SELECT COALESCE(PortOfLanding,'') AS '@detail'
FROM Landings.LandingHeaders
FOR XML PATH('SaleLine'), TYPE)
FROM Landings.LandingHeaders
WHERE Posted = 0
FOR XML PATH('Sale'), TYPE)
FOR XML PATH('abc')
Upvotes: 1