首页 > 解决方案 > 没有循环如何将值从 XML 节点插入到表中

问题描述

我有以下要求。

我有一个 XML 值变量。

我现在应该将此 XML 变量的值插入到表(表 A)中,但需要检查 XML 变量中的项目(一个接一个)是否已经存在于另一个表(表 B)中以及该个体的计数表 B 中的项目只有一次。

如果表 B 中不止一次/或不存在,请不要插入主表 - 表 A。

如何在不使用循环的情况下实现这一点。

Declare @Names xml
set @Names ='<List><CNames>One</CNames><CNames>Two</CNames></List>'

**When used below xml variable of values become a column of values :**

SELECT tbl.colname.value('text()[1]','varchar(10)') AS CN
FROM @Names ('/List/CNames') tbl(colname);

CN
-------
One
Two

现在在表 B 中——必须检查项目“一”和“二”是否存在,如果存在,它们只存在一次。

厌倦了使用运行良好的 while 循环,但希望在没有循环的情况下实现。

标签: sqlsql-serverxmlsql-server-2008

解决方案


由于您已经选择了要评估的行(@values在我的解决方案中),因此我从那里开始。

样本数据

-- existing table and data
declare @data table
(
    CN nvarchar(10)
);
insert into @data (CN) values
('One'),
('Three'),
('Three');

-- new values extracted from XML
declare @values table
(
    CN nvarchar(10)
);
insert into @values (CN) values
('One'),    -- exists 1x and will be inserted
('Two'),    -- does not exist and will not be inserted
('Three');  -- exists 2x and will not be inserted

解决方案

insert into @data (CN)
select v.CN
from @values v
cross apply (   select count(1) as 'Cnt'
                from @data d
                where d.CN = v.CN ) c
where c.Cnt = 1;

结果

select d.CN
from @data d
order by d.CN;


CN
----------
One
One      --> new inserted value
Three
Three

推荐阅读