Variable in T-SQL
I have the code T-SQL as follows:
declare @xml xml = N'
<a abb="122">
<b>
</b>
</a>
<a abb="344">
<b>
</b>
</a>';
declare @T table (XMLCol xml);
insert into @T values (@xml);
declare @sql varchar(max);
set @sql = 'update @T set
XMLCol.modify(''
replace value of (/a/@abb)[1]
with 888'');';
exec (@sql);
When I execute, a fault segment appears:
Msg 1087, Level 15, State 2, Line 1
Must declare the table variable "@T".
How to declare variable @T to be un开发者_如何学编程derstand?
You can use a temp table instead of table variable.
declare @xml xml = N'
<a abb="122">
<b>
</b>
</a>
<a abb="344">
<b>
</b>
</a>';
create table #T (XMLCol xml);
insert into #T values (@xml);
declare @sql varchar(max);
set @sql = 'update #T set
XMLCol.modify(''
replace value of (/a/@abb)[1]
with 888'');';
exec (@sql);
drop table #T
You cannot use the EXEC statement or sp_executesql stored procedure to run a dynamic SQL Server query that refers a table variable, if the table variable was created outside the EXEC statement or sp_executesql stored procedure.
Use a temp table instead.
Because you need to declare everything inside the dynamic part of the query. In your case i still don´t understand why you need the dynamic query, but if it´s necesary it should look like:
declare @sql varchar(max);
set @sql = '
declare @xml xml = N''
<a abb="122">
<b>
</b>
</a>
<a abb="344">
<b>
</b>
</a>'';
declare @T table (XMLCol xml);
insert into @T values (@xml);
update @T set
XMLCol.modify(''
replace value of (/a/@abb)[1]
with 888'');';
exec (@sql);
Table variables are not seen in the inner SPs so you should define a temporary table there not a table variable.
Because your @sql is executed on a different execution block so it will not find it. You need to declare your @t inside the "@sql" variable, including all transactions related to your @t.
declare @xml xml = N'
<a abb="122">
<b>
</b>
</a>
<a abb="344">
<b>
</b>
</a>';
declare @T table (XMLCol xml);
insert into @T values (@xml);
select * from @t
update @T set XMLCol.modify('replace value of (/a/@abb)[1] with 888');
select * from @t
This will work for your result
精彩评论