0

我想问一下使用OpenXML解析XML时如何在SQL Server中抛出错误。这是微软的一个例子:

Insert Into Employee 
SELECT   EmployeeId, FirstName, LastName
    FROM       OPENXML (@hdoc, '/NewDataSet/Employee',1)
WITH (EmployeeId Integer, FirstName varchar(100),  LastName varchar(100))  XMLEmployee
Where XMLEmployee.EmployeeId Not IN (Select EmployeeID from Employee)

如果根节点存在但其中没有 Employee 怎么办?

谢谢

4

1 回答 1

0

试试这个——

DECLARE @XML XML
SELECT @XML = '<NewDataSet></NewDataSet>'

IF NOT EXISTS(
    SELECT 1 
    WHERE @XML.exist('/NewDataSet/Employee') = 1
) RAISERROR('Employee not exists', 16, 1)

完整答案(可能是错误答案,因为我需要查看 XML 结构) -

DECLARE @XML XML
SELECT @XML = '<NewDataSet></NewDataSet>'

IF NOT EXISTS(
    SELECT 1 
    WHERE @XML.exist('/NewDataSet/Employee') = 1
) RAISERROR('Employee not exists', 16, 1)

INSERT INTO dbo.Employee (EmployeeId, FirstName, LastName)
SELECT
      t.c.value('@EmployeeId', 'INT')
    , t.c.value('@FirstName', 'VARCHAR(100)')
    , t.c.value('@LastName', 'VARCHAR(100)') 
FROM @XML.nodes('/NewDataSet/Employee') t(c)
WHERE t.c.value('@EmployeeId', 'INT') NOT IN (
    SELECT EmployeeID 
    FROM dbo.Employee
)
于 2013-08-02T04:47:32.530 回答