9

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

XML 数据类型方法“值”必须是字符串文字

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

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
于 2012-06-14T09:16:06.690 回答
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>'
于 2012-06-14T09:32:29.723 回答