XML数据类型的“value”方法必须是一个字符串字面量。

9
如何修改我的查询以避免出现此错误:
XML数据类型方法“value”必须是字符串文字。
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
2个回答

14

在 value 方法中不能像这样将变量连接为字符串。您需要使用 sql:variable("@VariableName")

因此,您的示例应该是这样的:

Declare @Count Int = 1 
While(@count <= @j) 
Begin 
insert into mytable 
([Word]) 

Select ([XmlColumn].value(N'/word[sql:variable("@Count")]/@Entry)[1]','nvarchar(max)'))
    from OtherTable WHERE ID=2

请勿在变量名上使用引号:sql:variable("@VariableName") -> sql:variable(@VariableName) - HuRN

1

我想寻找一种不需要使用WHILE循环的方法来解决这个问题。主要问题是返回节点的项目位置,但我在这篇帖子的最后一个答案中找到了一个解决方法:http://social.msdn.microsoft.com/Forums/nl/sqlxml/thread/46a7a90d-ebd6-47a9-ac56-c20b72925fb3

因此,替代方法将是:

insert into mytable ([Word]) 
select word from (
    Select 
        words.value('@entry','nvarchar(max)') as word,
        words.value('1+count(for $a in . return $a/../*[. << $a])', 'int') as Pos   
    from
        OtherTable ot
        cross apply ot.XMLColumn.nodes('words/word') x(words)
) sub where Pos <= @j

基本上,内部查询返回每个单词及其位置,可以通过外部查询进行过滤。

参考我的OtherWords表的定义如下:

create table OtherTable (XMLColumn xml)
insert OtherTable (XMLColumn)
select '<words><word entry="Wibble"/><word entry="Hello"/><word entry="World"/></words>'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接