您可以删除 while 循环并一次性执行插入nodes
以粉碎 XML。
insert into mytable([Word])
select N.value('@Entry', 'nvarchar(max)')
from OtherTable
cross apply XmlColumn.nodes('word') as T(N)
where ID = 2
如果@j
有限制要插入的行数,mytable
则可以改用它。
insert into mytable([Word])
select ID
from
(
select N.value('@Entry', 'nvarchar(max)') as ID,
row_number() over(order by T.N) as rn
from OtherTable
cross apply XmlColumn.nodes('word') as T(N)
where ID = 2
) T
where rn <= @j
如果您出于某种原因真的想使用循环,那么您可以这样做。
while @Count <= @j
begin
insert into mytable([Word])
select XMLColumn.value('(/word[sql:variable("@Count")]/@Entry)[1]', 'nvarchar(max)')
from OtherTable
where ID = 2