• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 3663
  • Last Modified:

Update multiple rows from another table where ID's equal

Hi,

I'm wondering if there is a way to update a table (tableA) with another table's values (tableB)  where the ID's equal.  For example:

TableA                                TableB
ID, Data, Cust                     ID, Jerry, John
1, xxx, John                         1, 333, null
2, xyx, John                         2, 222, null
3, yyx, John

What I want to do is update TableB column "John" with the data from TableA where the ID is the same and TableA.Customer = 'John'

I'm beating my head against a wall.  Any suggestions?


3, Null
4, xyyy
0
carmodyk
Asked:
carmodyk
  • 4
  • 2
5 Solutions
 
NickUpsonCommented:
The general form is:

update table1 set

field1 = (select fileld2 from table2 where...),
field2 = (select field3 from table2 where...),
...
where table1...

0
 
carmodykAuthor Commented:
I've tried that, I'm getting an error saying Multiple rows in singleton select
0
 
NickUpsonCommented:
this part of the query has to be unique with a where clause linking table1 to table2

field1 = (select fileld2 from table2 where...),

something like this, for a lookup change

field1 = (select fileld2 from table2 b where b.something = field1),

0
Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

 
NickUpsonCommented:
Another approach is, If you have a lot of records, writing a stored
procedure (or EXECUTE BLOCK with Firebird 2) should be better:

EXECUTE BLOCK
AS
DECLARE VARIABLE c1...
DECLARE VARIABLE c2...
DECLARE VARIABLE c3... etc. for each column
BEGIN
for select c1, c2, c3, ...
from table1
into :c1, :c2, :c3...
do update table2 set c1 = :c1, c2 = :c2, ... where pk = :pk;
END
0
 
NickUpsonCommented:
this might make it clearer

UPDATE TableA
SET FieldA =
(SELECT B.FieldB FROM TableA B
WHERE B.FieldID = TableA.FieldID)
0
 
Gary BenadeCommented:
To get around your singleton problem, change your query to something like this:

update table b
set john = (select max(data) from tablea where id = b.id)

HTH
Gary
0
 
carmodykAuthor Commented:
Thanks fellas, I've given up on the problem. But your help I'm sure will be useful in the future. :)
0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

  • 4
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now