简体   繁体   中英

Beginning SQL - adding the values of one column to another from separate tables

I am currently taking my first course in SQL and have encountered a bit of a problem. I will now try to explain what I am trying to do. I have this select statement which properly displays what I need. MY problem arises when I try to convert it into an UPDATE statement instead.

SELECT infobb02.uni+tempbb02.sal
from infobb02 JOIN tempbb02 ON infobb02.empno=tempbb02.empno;

In case its not obvious im adding value of uni from table infobb02 to sal in table tempbb02. I have tried all sorts of things to get it to be a permanent update but keep getting errors mostly

"SQL command not properly ended"

Any help is appreciated! Thanks.

Assuming that your query is:

SELECT i.uni + t.sal
FROM infobb02 i JOIN
     tempbb02 t
     ON i.empno = t.empno;

If you want to update tempbb02 , then:

update tempbb02 t
    set t.sal = t.sal +
                (select i.uni from infobb02 i where i.empno = t.empno)
    where exists (select 1 from infobb02 i where i.empno = t.empno);

Instead of using an UPDATE statement, you could use a MERGE:

merge into tempbb02 tgt
using infobb02 src
  on (tgt.empno = src.empno)
when matched then
update set tgt.sal = tgt.sal + src.uni;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM