Efficient method of inserting a column into a table based on another table
-
20-02-2021 - |
سؤال
Consider the following tables
CREATE TABLE Main (
id INT PRIMARY KEY,
state VARCHAR(255) DEFAULT NULL
)
CREATE TABLE ColorTable (
color VARCHAR(255),
state VARCHAR(255)
)
INSERT INTO Main (id, state) VALUES
(1, 'A'),
(2, 'B'),
(3, 'C'),
(4, 'B'),
(5, 'C'),
(6, 'A'),
(7, NULL)
INSERT INTO ColorTable (color, state) VALUES
('Yellow', 'A'),
('Red', 'B'),
('Green', 'C'),
('Black', NULL)
I would like to add a new column 'color' into the table 'Main'. I want this such that the color for each id is based on the state in 'Main', and the corresponding color in 'ColorTable'.
I can achieve this through the following:
ALTER TABLE main
ADD color VARCHAR(255)
UPDATE main
SET main.color = ColorTable.color
FROM main
LEFT JOIN ColorTable ON main.state = ColorTable.state
UPDATE main
SET color = 'Red'
WHERE state IS NULL
I am curious as to alternative methods of doing this–can I achieve the same result using a SELECT INTO or something else?
المحلول
No, you cannot alter the table structure and insert the data into new column in one statement.
But you can combine last 2 updates:
UPDATE main
SET main.color = CASE WHEN main.state IS NULL
THEN 'Red'
ELSE ColorTable.color
END
FROM main
LEFT JOIN ColorTable ON main.state = ColorTable.state
لا تنتمي إلى dba.stackexchange