如何将OPENXML数据加入我的内部联接查询?

时间:2012-10-10 19:42:23

标签: sql-server-2008 openxml

的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))

结果:

EmployeeID    EmpStatus
    1         Full Time
    2         Part Time

表格查询:

    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)

结果:

EmployeeID  Title         FirstName  LastName
    1   Engineering   Mike       Brown
    2   Programmer    Yves       Anthony

如何使用EmployeeID将OpenXML数据加入我的内部联接查询?

2 个答案:

答案 0 :(得分:1)

坚持使用OpenXML吗?这是旧的,它的遗产 - 使用原生XQuery功能通常更容易

尝试这样的事情:

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

这给了我一个输出:

enter image description here

答案 1 :(得分:0)

尽管另一个答案意味着在openxml中有一定程度的弃用,但我无法找到任何证据,也没有费心去解决如何做到这一点......你可以使用{ {1}}和openxml在同一时间。

在你的情况下,它是这样的:

join

h / t:http://www.informit.com/articles/article.aspx?p=26499&seqNum=3