1

I have this SQL...

UPDATE table1 t1
SET (t1.wert) = 
(select t2.bezeichnung from table2 t2 
where t1.id = t2.cpbezeichnung) 
where t1.id = t2.cpbezeichnung

... which I cant run because it says me that it doesnt know t2.cpbezeichnung in line #5.

How can I fix it?

4 Answers 4

3

Table with alias t2 is not defined for UPDATE query, so it's clearly not known at line 5. Table t2 is defined only inside subquery on lines 3 and 4.

What exactly are you trying to achieve with condition on line 5?

If do you want prevent setting NULL into t1.wert for rows where there is no appropriate record in table t2, then you need to replace condition on line 5

UPDATE table1 t1
SET (t1.wert) = 
(select t2.bezeichnung from table2 t2 where t1.id = t2.cpbezeichnung) 
where t1.id IN (SELECT t2.cpbezeichnung from table2)

This will set values in t1.wert only for records where t1.id exists in t2.cpbezeichnung.

Sign up to request clarification or add additional context in comments.

Comments

1

The t2 alias (along with table2) is only visible in the subquery. My guess is that you want

UPDATE table1 t1
  SET t1.wert = (select t2.bezeichnung 
                   from table2 t2 
                  where t1.id = t2.cpbezeichnung) 
where exists (select 1
                from table2 t2 
               where t1.id = t2.cpbezeichnung) 

which updates every row where there is a match between the two tables. If that's not what you want, posting a test case would be helpful.

Comments

0

When using correlated subqueries you cannot use an alias from the inner query in the outer query.

The outer query knows nothing about the inner query except its results.

Ref

Comments

0

You will have to use a Inner join on the two tables.

Something like

UPDATE table1 t1 INNERJOIN table t2 ON your_table_condition SET t1.wert = (select t2.bezeichnung from t2 where t1.id = t2.cpbezeichnung) where t1.id = t2.cpbezeichnung

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.