2013-08-02 65 views
0

我想問一下如何在SQL Server中拋出一個錯誤時,XML使用的OpenXML解析沒有發現任何節點如何拋出錯誤。下面是來自微軟的例子:當使用的OpenXML

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) 

如果根節點存在,但沒有員工的呢?

感謝

回答

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 
)