Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Update column based on another table

Author  Topic 

tnkrtrn
Starting Member

1 Post

Posted - 2010-07-15 : 15:38:10
Hi,

I'm trying to update a column in one table if another columns value equals a value in another table.

So table1 has 2 columns, ID and TEST. Table2 has 1 column, ID.

In table1 there are 5 records. The value of ID is 1,2,3,4,5. The TEST column is null for all the records.

In table2 there are 3 records. The value of ID is 1,3,5.

The query I'm trying to run should update the TEST column in table1 to 'success' where the value of ID in table1 matches the value of ID in table2.

Here is the sql I'm using.

update table1
set TEST='success'
where exists
(select * from table1
inner join table2
on table1.ID=table2.ID);

When I run that it updates all the records in table1 so that the value for TEST is success. I thought there was something wrong with my select statement but

select * from table1 inner join table2 on table1.ID=table2.ID

returns 3 records which is correct so I'm assuming there must be something wrong with the where exists part of my update statement.

I would be extremely grateful if someone could look at that statement and tell me what I'm doing wrong.

Thanks

webfred
Master Smack Fu Yak Hacker

8781 Posts

Posted - 2010-07-15 : 15:47:47
update t1
set TEST='success'
from table1 as t1
inner join table2 as t2 on t1.id = t2.id

Your solution can't work because your query in the EXISTS() has no relation to the outer query.


No, you're never too old to Yak'n'Roll if you're too young to die.
Go to Top of Page
   

- Advertisement -