I have a question regarding the following syntax. Is there a cleaner way to roll this up into one statement rather than two. I\'ve tried several iterations but this seems to b
You can make a temporary table or a table variable containing the updates you want to do, then run the UPDATE
statement linking the table to the table you intend to update.
Note that for two updates, you get two statements: the INSERT
into the update table and the UPDATE
statement itself. The number of statements remains two though for as many updates you need to do.
CREATE TABLE #employee (emp_id VARCHAR(9) NOT NULL PRIMARY KEY,hire_date DATE NOT NULL);
INSERT INTO #employee (emp_id,hire_date)
VALUES ('PMA42628M','2013-06-05'),('PSA89086M','2013-06-05');
CREATE TABLE #target_updates(emp_id VARCHAR(9) NOT NULL,hire_date DATE NOT NULL);
INSERT INTO #target_updates (emp_id,hire_date)
VALUES ('PMA42628M','1979-03-15'),('PSA89086M','1988-12-22');
UPDATE
#employee
SET
hire_date=tu.hire_date
FROM
#employee AS e
INNER JOIN #target_updates AS tu ON
tu.emp_id=e.emp_id;
SELECT
*
FROM
#employee
ORDER BY
emp_id;
DROP TABLE #target_updates;
DROP TABLE #employee;