I have the following sample data:
create table employee (id int,emp_name varchar(50),project_name varchar(50));
insert into employee(id,emp_name) values(1,'Smith');
insert into employee(id,emp_name) values(2,'Jill');
insert into employee(id,emp_name) values(3,'Hana');
create table employee_project (emp_id int,project_id int);
insert into employee_project(emp_id,project_id) values(1,101);
insert into employee_project(emp_id,project_id) values(2,201);
insert into employee_project(emp_id,project_id) values(3,301);
create table project (id int,pro_name varchar(50));
insert into project(id,pro_name) values(101,'School');
insert into project(id,pro_name) values(201,'Tax');
insert into project(id,pro_name) values(301,'Road');
I need to update table employee
column project_name
.
Update Queries:
Try 1: Failed – Error : relation "e" does not exist
update e
set project_name = p.pro_name
from employee e
inner join employee_project ep on ep.emp_id = e.id
inner join project p on p.id = ep.project_id;
Try 2: Failed – Error : missing FROM-clause entry for table "p"
update employee
set project_name = p.pro_name
from employee e
inner join employee_project ep on ep.emp_id = e.id
inner join project p on p.id = ep.project_id;
Try 3: Works
update employee
set project_name = p.pro_name
from employee_project ep
inner join project p on p.id = ep.project_id
WHERE ep.emp_id = employee.id;
The try 3 works fine but not sure about SQL ANSI standard and also how will it gonna work for different joins(LEFT, RIGHT) when base table having number of different joins.
Note: I am running these queries from SQL Server Management Studio.
2
Answers
SQL Server accepts a special syntax for UPDATE with JOINs that does not exists in the ISO SQL standard.
This syntax is quicker rather the official ones that use IN, ALL, ANY or EXISTS operators which are complicated to write…
So this syntax is not available in some other RDBMS !
WARNING : in the case of the UPDATE and given the cardinalities involved, the update may be ambiguous because it is arbitrary. Indeed, if the columns contained in the value expressions to update come from joined table(s) whose cardinality is greater than 1 for each row to update, then the value assigned will be any of the values resulting from the join !
As an example in my next SQL book, I give the following SQL script :
The result will be :
If I add the following index :
The result is now :
The errors you encountered occur in Babelfish v.2.3.x and before. In 2.4.0 or later, these have been fixed.