2

I need output something like this

<Employee EmpID="4">
  <FirstName>Rob</FirstName>
  <LastName>Walters</LastName>
</Employee>
<Employee EmpID="168">
  <FirstName>Rob</FirstName>
  <MiddleName>T</MiddleName>
  <LastName>Caron</LastName>
</Employee>

But the SQL to do this:

SELECT e.EmployeeID AS "@EmpID",
   c.FirstName, 
   c.MiddleName, c.LastName
FROM Employee AS e 
INNER JOIN Contact AS c 
ON c.ContactID = e.ContactID
WHERE c.FirstName = 'Ross'
FOR XML PATH (''), ROOT ('Employees'); 

Return this error:

SQL Server Database Error: Row tag omission (empty row tag name) cannot be used with attribute-centric FOR XML serialization.

See the SQLFiddle:

SQLFiddle

5
  • SELECT (SELECT e.EmployeeID AS "@EmpID" FOR XML PATH ('EmployeeID'), TYPE), c.FirstName, c.MiddleName, c.LastName ... FOR XML PATH ('Employee'), ROOT ('Employees'); is probably what you're after. Commented Aug 16, 2017 at 22:11
  • Hey @ZLK Thanks, but is not that... the result from your code was: <Employee><Employee EmpID="256"/><FirstName>Ross</FirstName><MiddleName></MiddleName><LastName>Geller</LastName></Employee> SQLFiddle but i need <Employee EmpID="256"><FirstName>Ross</FirstName><MiddleName></MiddleName><LastName>Geller</LastName></Employee> Commented Aug 16, 2017 at 22:19
  • 1
    Uh, then all you should need to do is change for xml path ('') to for xml path ('Employee') in your current query. Commented Aug 16, 2017 at 22:43
  • For reference: Link: "Red Gate - Using the FOR XML Clause" Commented Aug 16, 2017 at 22:44
  • @ZLK This work well, thanks.... SQLFiddle Commented Aug 16, 2017 at 22:48

1 Answer 1

3

The best way to do is using the right code:

SELECT 
e.EmployeeID AS "@EmpID",
c.FirstName, 
c.MiddleName, c.LastName
FROM Employee AS e 
INNER JOIN Contact AS c 
ON c.ContactID = e.ContactID
WHERE c.FirstName = 'Ross'
FOR XML PATH ('Employee')
;

Like the right SQLFiddle: http://www.sqlfiddle.com/#!6/3a159/8/0

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.