I have a problem referencing a table variable in a update statement. Seems I can’t use the @a.id column (the compiler says it’s not declared).
The following example was written only to illustrate the problem, meaning that I know that I can solve the problem in the current example renaming the column id and avoiding the @a.id reference, but it’s not a option, I really can’t do that. I saw some solutions using the from statement to alias the table being updated, but in this example I’m using the from statement for something else. Is there another way to solve it?
declare @a table
(
id int not null,
name varchar(100) null
)
insert into @a (id, name) values (1, null)
insert into @a (id, name) values (2, null)
insert into @a (id, name) values (3, null)
declare @b table
(
id int not null,
name varchar(100) null
)
insert into @b (id, name) values (1, 'one')
insert into @b (id, name) values (2, 'two')
update @a
set
name = f.name
from
(
select
id,
name
from @b
where
id = @a.id
) f
where
@a.id = f.id
Try something like this:
And BTW following will work too: