Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

Updating one table using another

Hello,

I have one problem and don't know how to solve this.
My tables are more complex, but let's simplify it.

Let's assume that there are two tables, for example, T1 and T2
Below is the structure:

------

T1:

rownum INT
id INT
val INT

T2:

id INT
val INT

--------

Column ID is the match between two tables.
Rownum is identity in the T1 table.

Below are records in each table:

----

T1:

rownum id val
1 1 NULL
2 1 NULL

3 2 NULL
4 2 NULL
5 2 NULL

T2:

id val
1 22215
1 22283
1 22223

2 22243
2 22252

---

I have to update t1.val using t2.val by matching them on ID.

As you see, ID is either 1 or 2.

When ID = 1, there are two rows in t1 and three in t2
When ID = 2, there are three rows in t1 and only two in t2

When ID = 1
Since there are only two rows to update in t1, we will take first two values
from t2, and not the third one.

When ID = 2
Since there are only two rows from t2 to take, two rows in t1 will be updated.
third one will remain null

The problem is I have to put different t2.val in each t1.val even if ID is
the same.

Therefore, after update, T1 should look like this:

rownum id val

1 1 22215
2 1 22283

3 2 22243
4 2 22252
5 2 NULL

Please let me know if there is a way how to do it using UPDATE statement
and not a cursor.

Thank you.

John
[1778 byte] By [John] at [2007-11-9 21:11:18]