问题
OpenXML:
DECLARE @idoc int
DECLARE @doc varchar(1000)
SET @doc =
'<ROOT>
<Employee EmployeeID = "1" EmpStatus = "Full Time"/>
<Employee EmployeeID = "2" EmpStatus ="Part Time" />
</ROOT>'
EXEC sp_xml_preparedocument @idoc OUTPUT, @doc
SELECT *
FROM OPENXML (@idoc, '/ROOT/Employee',1)
WITH (EmployeeID varchar(10),
EmpStatus varchar(20))
Results:
EmployeeID EmpStatus
1 Full Time
2 Part Time
Table query:
SELECT hr.EmployeeID, hr.Title, c.FirstName,c.LastName
FROM HumanResources.Employee hr WITH (NOLOCK)
INNER JOIN ContactInfo c WITH (NOLOCK)
ON hr.ContactID = c.ContactID
Where hr. EmployeeID IN ( 1, 2)
Results:
EmployeeID Title FirstName LastName
1 Engineering Mike Brown
2 Programmer Yves Anthony
How to join OpenXML data to my inner join query using EmployeeID
?
回答1:
Do you insist on using OpenXML? It's old, it's legacy - using the native XQuery functions typically is much easier.
Try something like this:
DECLARE @Employees TABLE (EmployeeID INT, Title VARCHAR(20), FirstName VARCHAR(20),LastName VARCHAR(20))
INSERT INTO @Employees VALUES(1, 'Engineering', 'Mike', 'Brown')
INSERT INTO @Employees VALUES(2, 'Programmer', 'Yves', 'Anthony')
DECLARE @doc XML
SET @doc = '<ROOT>
<Employee EmployeeID = "1" EmpStatus = "Full Time"/>
<Employee EmployeeID = "2" EmpStatus ="Part Time" />
</ROOT>'
;WITH XmlCTE AS
(
SELECT
EmpID = Empl.value('@EmployeeID', 'int'),
EmpStatus = Empl.value('@EmpStatus', 'varchar(10)')
FROM @doc.nodes('/ROOT/Employee') AS Tbl(Empl)
)
SELECT
e.*, x.EmpStatus
FROM
@Employees e
INNER JOIN
xmlcte x ON e.EmployeeID = x.EmpID
This gives me an output of:

回答2:
Despite the other answer implying a level of deprecation in openxml
that I can find no evidence of, and not bothering to address how to do it anyway... you can use openxml
and join
at the same time.
In your case, it'd be something like this:
select
x.*,
hr.EmployeeID, hr.Title, c.FirstName, c.LastName
from
openxml (@IDoc, '/ROOT/Employee',1)
with (
EmployeeID varchar(10),
EmpStatus varchar(20)
) as x
inner join HumanResources.Employee hr with (nolock) on
x.EmployeeID = hr.EmployeeID
inner join Contactinfo c with (nolock)
on hr.ContactID = c.ContactID;
h/t: http://www.informit.com/articles/article.aspx?p=26499&seqNum=3
来源:https://stackoverflow.com/questions/12827126/how-to-join-openxml-data-to-my-inner-join-query