SQL openXML 如何使用for循环
这是我的代码,我在逐一插入 xml 元素值时遇到问题。 如何为此设置 for 循环
DECLARE @x VARCHAR(8000)
SET @x =
'<authors>
<author>
<firstname>Michael</firstname>
<lastname>Howard</lastname>
</author>
<author>
<firstname>David</firstname>
<lastname>LeBlanc</lastname>
</author>
<author>
<firstname>adad</firstname>
<lastname>asdad</lastname>
</author>
<author>
<firstname>adad</firstname>
<lastname>asdad</lastname>
</author>
</authors>'
DECLARE @h INT
DECLARE @h1 VARCHAR(MAX)
EXECUTE sp_xml_preparedocument @h OUTPUT, @x
SELECT @h1= firstname
FROM OPENXML(@h, '/authors/author',2)
WITH(
firstname VARCHAR(20)
)
select NAME from temps WHERE NAME=@h1
if @@ROWCOUNT=0
Begin
INSERT INTO temps(NAME) VALUES (@h1)
END
EXECUTE sp_xml_removedocument @h
现在我的代码只插入最后一个 xml 元素,我想一个接一个地执行此操作..告诉我解决方案或想法
This is my code I have problem in inserting the xml element values one by one..
How to put for loop for this
DECLARE @x VARCHAR(8000)
SET @x =
'<authors>
<author>
<firstname>Michael</firstname>
<lastname>Howard</lastname>
</author>
<author>
<firstname>David</firstname>
<lastname>LeBlanc</lastname>
</author>
<author>
<firstname>adad</firstname>
<lastname>asdad</lastname>
</author>
<author>
<firstname>adad</firstname>
<lastname>asdad</lastname>
</author>
</authors>'
DECLARE @h INT
DECLARE @h1 VARCHAR(MAX)
EXECUTE sp_xml_preparedocument @h OUTPUT, @x
SELECT @h1= firstname
FROM OPENXML(@h, '/authors/author',2)
WITH(
firstname VARCHAR(20)
)
select NAME from temps WHERE NAME=@h1
if @@ROWCOUNT=0
Begin
INSERT INTO temps(NAME) VALUES (@h1)
END
EXECUTE sp_xml_removedocument @h
Now my code is inserting only last xml element I want to do it one after the another.. tell me the solution or idea
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果你这样做:
你可以轻松地执行
insert into ...
而不是执行循环NOTE我添加了row_num,因为它看起来你只想插入我从您的查询中了解到的第二行的值
If you do something like this:
You can easily do an
insert into ...
instead of doing a loopNOTE I added row_num because it looked like you only wanted to insert the second row's value from what I understood from your query
您没有描述为什么要处理 XML,所以我会猜测。看来您正在
temps
表中查找特定的firstname
值,如果未找到,则添加它。我将使用表变量@names
进行演示。LEFT OUTER JOIN 与 WHERE 条件一起使用来标识 @firstnames 表变量中而不是 [firstnames] 表中的名字。只要有可能,就尽量避免在 SQL 中迭代数据,并尝试使用基于集合的操作。
You have not described why you are processing the XML, so I will guess. It appears you are looking for a specific
firstname
value in thetemps
table and if it is not found then you add it. I'll demonstrate with a table variable,@names
.The LEFT OUTER JOIN is used with a WHERE condition to identity firstnames that are in the @firstnames table variable and not in the [firstnames] table. Whenever possible try to avoid iterating through data in SQL and try to use set based operations.