How can I write single UPDATE query to change value of COL1 to ‘X’ if COL2 < 10 otherwise change it to ‘Y’, where the following two tables are linked by ID
CREATE TABLE TEMP(ID TINYINT, COL1 CHAR(1))
INSERT INTO TEMP(ID,COL1) VALUES (1,'A')
INSERT INTO TEMP(ID,COL1) VALUES (2,'B')
INSERT INTO TEMP(ID,COL1) VALUES (11,'A')
INSERT INTO TEMP(ID,COL1) VALUES (17,'B')
CREATE TABLE TEMP2(ID TINYINT, COL2 TINYINT)
INSERT INTO TEMP2(ID,COL2) VALUES (1,1)
INSERT INTO TEMP2(ID,COL2) VALUES (2,5)
INSERT INTO TEMP2(ID,COL2) VALUES (11,10)
INSERT INTO TEMP2(ID,COL2) VALUES (17,15)
Thanks in advance!开发者_StackOverflow
You cannot update two tables at once, in a single statement.
However, in your case, if I understand you correctly, what you're really trying to do is update TEMP based on values from TEMP2 - that's of course possible
UPDATE TEMP
SET COL1 = CASE
WHEN TEMP2.COL2 < 10 THEN 'X'
ELSE 'Y'
END
FROM TEMP2
WHERE TEMP.ID = TEMP2.ID
update TEMP
set COL1 = (case when TEMP2.COL2 < 10 then 'X' else 'Y' end)
from TEMP
inner join TEMP2 on TEMP.ID = TEMP2.ID
精彩评论