没有循环如何从 XML 节点将值插入 table
Without loop how to insert values into table from XML node
我有以下需求
我有一个 XML 值变量。
我现在应该将此 XML 变量的值插入到 table (Table A),但需要检查 [= =38=] 变量已经存在于另一个 table (Table B) 中,并且 table B 中存在的单个项目的计数只有一次。
如果不止一次/或不存在于 Table B 中,请不要插入主 table - Table 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
现在 Table B -- 必须检查项目 'One' 和 'Two' 是否存在,如果存在则它们只存在一次。
厌倦了使用 while 循环,它工作正常,但想要实现无循环。
由于您已经选择要评估的行(@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
我有以下需求
我有一个 XML 值变量。
我现在应该将此 XML 变量的值插入到 table (Table A),但需要检查 [= =38=] 变量已经存在于另一个 table (Table B) 中,并且 table B 中存在的单个项目的计数只有一次。
如果不止一次/或不存在于 Table B 中,请不要插入主 table - Table 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
现在 Table B -- 必须检查项目 'One' 和 'Two' 是否存在,如果存在则它们只存在一次。
厌倦了使用 while 循环,它工作正常,但想要实现无循环。
由于您已经选择要评估的行(@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