How to change my T-SQL query so that this error doesn't occur:
如何更改我的T-SQL查询,以便不会发生此错误:
'The argument 1 of the XML data type method "value" must be a string literal.'
'XML数据类型方法“value”的参数1必须是字符串文字。
T-SQL code:
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 个解决方案
#1
19
You must use sql variable implicitly:
您必须隐式使用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
#2
5
You can remove the while loop and do the insert in one go using nodes
to shred the XML.
您可以删除while循环并使用节点一次性执行插入以粉碎XML。
insert into mytable([Word])
select N.value('@Entry', 'nvarchar(max)')
from OtherTable
cross apply XmlColumn.nodes('word') as T(N)
where ID = 2
If @j
is there to limit the number of rows you want to insert to mytable
you can use this instead.
如果@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
If you for some reason really want to use the loop then you can do like this instead.
如果你出于某种原因真的想要使用循环,那么你可以这样做。
while @Count <= @j
begin
insert into mytable([Word])
select XMLColumn.value('(/word[sql:variable("@Count")]/@Entry)[1]', 'nvarchar(max)')
from OtherTable
where ID = 2
#1
19
You must use sql variable implicitly:
您必须隐式使用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
#2
5
You can remove the while loop and do the insert in one go using nodes
to shred the XML.
您可以删除while循环并使用节点一次性执行插入以粉碎XML。
insert into mytable([Word])
select N.value('@Entry', 'nvarchar(max)')
from OtherTable
cross apply XmlColumn.nodes('word') as T(N)
where ID = 2
If @j
is there to limit the number of rows you want to insert to mytable
you can use this instead.
如果@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
If you for some reason really want to use the loop then you can do like this instead.
如果你出于某种原因真的想要使用循环,那么你可以这样做。
while @Count <= @j
begin
insert into mytable([Word])
select XMLColumn.value('(/word[sql:variable("@Count")]/@Entry)[1]', 'nvarchar(max)')
from OtherTable
where ID = 2