【问题标题】:How to check if an item already exists in table when inserting from a XML从 XML 插入时如何检查表中是否已存在项目
【发布时间】:2016-05-03 06:12:49
【问题描述】:

我需要从 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 不是很好,任何帮助将不胜感激。

【问题讨论】:

  • 首先将您的 XML 数据插入 table_variable 或 temp_table 并将其与您的实际表合并。

标签: sql xml sql-server-2012


【解决方案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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-21
    • 1970-01-01
    • 2017-04-23
    相关资源
    最近更新 更多