在SQL Server中如果要借用update @t set col1=t2.col1 from t2 where @t.col1=t2.col1的语句来更新表变量中的数据时,会得到一个“must declare variant @t”的错误消息,原因是这里条件语句中的@t会被解析器当作一个变量来看待,故此不能做出正确的执行。
后找到解决办法:只须将@t再声明一次即可,声明为别名,如下即可:
update @t set col1=t2.col1 from @t t1, t2 where t1.col1=t2.col1
至此,问题解决。
测试代码:


1
2 declare @t table(id int,col1 varchar(10))
3 create table #t1(id int ,col1 varchar(10))
4
5 insert into #t1
6 select 1,'a'
7 insert into #t1
8 select 2,'b'
9 insert into @t select * from #t1
10 select * from @t
11
12 update #t1 set col1='c' where id=1
13
14 update @t set col1=t1.col1 from @t t,#t1 t1 where t.id=t1.id
15
16 select * from @t
17
18 drop table #t1
2 declare @t table(id int,col1 varchar(10))
3 create table #t1(id int ,col1 varchar(10))
4
5 insert into #t1
6 select 1,'a'
7 insert into #t1
8 select 2,'b'
9 insert into @t select * from #t1
10 select * from @t
11
12 update #t1 set col1='c' where id=1
13
14 update @t set col1=t1.col1 from @t t,#t1 t1 where t.id=t1.id
15
16 select * from @t
17
18 drop table #t1