2

Is the following posible on SQL? (Using SQLITE3)

UPDATE Table SET
Value1 = (SELECT ...)
Value2 = Value3/Value1; # The new value1!!! Not the value currently on the DB

Right now I need to do something like:

UPDATE Table SET
Value1 = (SELECT ...)
Value2 = Value3/(SELECT ...);

This makes the code quite long. Imagine it is not only Value1 I am updating but other fields too.

So the only solution I found is to do 2 UPDATES. First:

UPDATE Table SET
Value1 = (SELECT ...);

And then

UPDATE Table SET
Value2 = Value3/Value1;

Anyone with a more "beautiful" way of doing this?

Thanks,

Yona
  • 571
  • 7
  • 23

3 Answers3

1

In SQLite 3.8.3 or later, you can use a common table expression:

WITH u(v) AS (
    SELECT ...
)
UPDATE MyTable
SET Value1 = (SELECT v FROM u),
    Value2 = Value3 / (SELECT v FROM u);

(This even works with correlated subqueries.)

CL.
  • 173,858
  • 17
  • 217
  • 259
0

Maybe you can try replace

replace into table2
(Value1 , Value2)
select src.Value1 , src.Value3 / src.Value1
from table1 src

In sql you cant do UDPATE ... FROM as explain in this answer

Community
  • 1
  • 1
Juan Carlos Oropeza
  • 47,252
  • 12
  • 78
  • 118
  • This will delete any old rows, so the values in the other columns will be lost. – CL. Oct 14 '15 at 16:26
-1

You can do like this :

update Table1 set szNo = KO.nNo 
from 
(select nNo From Table2) KO
Viandry
  • 73
  • 8