16

如何更改我的 T-SQL 查询,以免发生此错误:

'XML 数据类型方法“value”的参数 1 必须是字符串文字。'

T-SQL 代码:

Declare @Count Int = 1
While(@count <= @j)
Begin
insert into mytable
([Word])
Select ([XmlColumn].value(N'word['+Cast(@Count as nvarchar(2))+']/@Entry','nvarchar(max)'))
    from OtherTable WHERE ID=2
4

2 回答 2

25

您必须隐式使用 sql 变量:

Declare @Count Int = 1
While(@count <= @j)
Begin
insert into mytable
([Word])
Select ([XmlColumn].value('(/word[sql:variable("@Count")]/@Entry)[1]','nvarchar(max)'))
    from OtherTable WHERE ID=2
于 2012-05-02T06:38:40.473 回答
5

您可以删除 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
于 2012-05-02T06:18:47.327 回答