I am staring at an Update statement, with CASE conditions on two columns, and I cannot understand why it does not work properly.
(This is actually an expansion of thread183-266358)
We are updating TableA from TableB, as follows:
[tt]
TableB data looks like:
id type dollars
1 type1 25
1 type2 30
2 type2 50
2 type1 7
TableA before update looks like:
id type1_dollars type2_dollars
1 0 0
2 0 0
TableA after update should be:
1 25 30
2 7 50
BUT TableA after update actually is:
1 0 30
2 0 50
[/tt]
--------------------------------------
As you can see, the type1_dollars is not being updated. But type2_dollars are.
Here is my Update statement
[tt]
Update a SET
a.type1_dollars =
(CASE b.type when 'type1' then b.dollars
else a.type1_dollars END),
a.type2_dollars =
(CASE b.type when 'type2' then b.dollars
else a.type2_dollars END)
From tablea a INNER JOIN tableb b
ON a.id = b.id
WHERE b.type IN ('type1', 'type2')
[/tt]
-----------------------------------
If you are interested, here's some script to create the tables.
CREATE TABLE TableA (
id int NOT NULL,
type1_dollars int,
type2_dollars int,
Primary Key (id)
)
INSERT TableA Values (1,0,0)
INSERT TableA Values (2,0,0)
CREATE TABLE TableB (
id int NOT NULL,
type varchar(5),
dollars int,
Primary Key (id, type)
)
INSERT TableB VALUES (1,'type1',25)
INSERT TableB VALUES (1,'type2',30)
INSERT TableB VALUES (2,'type1',7)
INSERT TableB VALUES (2,'type2',50)
------------------------------------
(This is actually an expansion of thread183-266358)
We are updating TableA from TableB, as follows:
[tt]
TableB data looks like:
id type dollars
1 type1 25
1 type2 30
2 type2 50
2 type1 7
TableA before update looks like:
id type1_dollars type2_dollars
1 0 0
2 0 0
TableA after update should be:
1 25 30
2 7 50
BUT TableA after update actually is:
1 0 30
2 0 50
[/tt]
--------------------------------------
As you can see, the type1_dollars is not being updated. But type2_dollars are.
Here is my Update statement
[tt]
Update a SET
a.type1_dollars =
(CASE b.type when 'type1' then b.dollars
else a.type1_dollars END),
a.type2_dollars =
(CASE b.type when 'type2' then b.dollars
else a.type2_dollars END)
From tablea a INNER JOIN tableb b
ON a.id = b.id
WHERE b.type IN ('type1', 'type2')
[/tt]
-----------------------------------
If you are interested, here's some script to create the tables.
CREATE TABLE TableA (
id int NOT NULL,
type1_dollars int,
type2_dollars int,
Primary Key (id)
)
INSERT TableA Values (1,0,0)
INSERT TableA Values (2,0,0)
CREATE TABLE TableB (
id int NOT NULL,
type varchar(5),
dollars int,
Primary Key (id, type)
)
INSERT TableB VALUES (1,'type1',25)
INSERT TableB VALUES (1,'type2',30)
INSERT TableB VALUES (2,'type1',7)
INSERT TableB VALUES (2,'type2',50)
------------------------------------