从XML

时间:2016-05-03 06:12:49

标签: sql xml sql-server-2012

我需要从XML向我的表插入数据。我必须在插入数据之前检查唯一性。

我目前的代码是:

@declare @existing_id INT=0

DELETE FROM [maintenance.master].[oper_cat]
WHERE  [oper_cat_id] IN (SELECT tab.col.value('Id[1]','int')  
                         FROM @oper_cat.nodes('//Sample') AS tab(col)
                         WHERE CAST(tab.col.value('Deleted[1]','bit') AS BIT) = 1)  

;WITH Sample AS
(   
    SELECT 
        tab.col.value('Id[1]','int') AS [Id],
        tab.col.value('Title[1]','nvarchar(100)') AS [Title],
        tab.col.value('Type[1]','char(1)') AS [Type],
    FROM  
        @oper_cat.nodes('//Sample') AS tab(col)  
    WHERE 
        CAST(tab.col.value('Deleted[1]','bit') AS BIT) = 0
) 
SET @existing_id = (SELECT id 
                    FROM sample_table 
                    WHERE title = Sample.Title AND type = Sample.Type)

IF  @existing_id = 0
BEGIN
    INSERT INTO sample_table(id, title, type)
    VALUES(Sample.Id, Sample.Title, Sample.Type)
END

显然上面的代码不起作用。当我试图获取现有ID时,我收到了错误消息。在将值插入表之前,如何检查这一点。我对SQL不太了解任何帮助都会非常感激。

1 个答案:

答案 0 :(得分:1)

试试这样:

--a volatile table to get your XML row-wise
DECLARE @tmpTable TABLE(Id INT, Deleted BIT,Title VARCHAR(150),[Type] CHAR(1));
INSERT INTO @tmpTable 
SELECT  tab.col.value('Id[1]','int') AS [Id],
        tab.col.value('Deleted[1]','bit') AS Deleted,
        tab.col.value('Title[1]','nvarchar(100)') AS [Title],
        tab.col.value('Type[1]','char(1)') AS [Type]
FROM  
    @oper_cat.nodes('//Sample') AS tab(col);  

--Delete all with Deleted=1
DELETE FROM [maintenance.master].[oper_cat]
WHERE  [oper_cat_id] IN (SELECT Id FROM @tmpTable WHERE Deleted=1);

--Insert all with Deleted=0
INSERT INTO sample_table(id, title, type)
SELECT Id,Title,[Type]
FROM @tmpTable 
WHERE Deleted=0;