sql - 没有循环如何将值从 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 循环,但希望在没有循环的情况下实现。
解决方案
由于您已经选择了要评估的行(@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
推荐阅读
- c++ - Unreal Engine 4.25 Github版本:无法编译C++代码
- flutter - Dart / Flutter测试肘,比较预期和实际的问题
- openshift - IBM Cloud-Native Toolkit 的 oc 管道错误
- html - CSS奇怪的顶部填充
- python - 使用 Pillow 为灰度图像着色
- laravel - 如何在 php/laravel 中为同一控制器上的多个端点生成 swagger api-docs.json
- regex - 在熊猫中将文本读入表格格式
- reactjs - 从函数返回后反应状态不更新
- java - SageMaker 异常
- sockets - ebpf:验证者在哪里打印它的消息?