Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

subqueries in UPDATE SET (sql server 2005)

I have a question about using subqueries in an Update statement. My example:

UPDATE TRIPS
   SET locations = city + ', ' FROM (select Distinct city 
                                       from poi 
                                      where poi.trip_guid = trips.guid) 

Is it possible to refer to main table value (trips.guid) in subqueries?

When i try to use trips.guid I get the error:

"The multi-part identifier "trips.guid" could not be bound."

The clause 'select Distinct city from poi' return more that one city.

like image 367
itdebeloper Avatar asked Apr 06 '10 16:04

itdebeloper


People also ask

Can we use subquery in UPDATE statement?

UPDATE Subquery Finally, you can use a subquery in an UPDATE statement for the table to be updated. In the previous examples, we have just used the product table. However, you can use a subquery instead of the product table, which will return a result set that can be updated.

Can we use subquery in UPDATE statement true or false?

A subquery-also referred to as an inner query or inner select-is a SELECT statement embedded within a data manipulation language (DML) statement or nested within another subquery. You can use subqueries in SELECT, INSERT, UPDATE, and DELETE statements wherever expressions are allowed.

Can I use from clause in UPDATE?

UPDATE statements with a FROM clause are often used to update information in a table based on a table-valued parameter (TVP), or to update columns in a table in an AFTER trigger. For the scenario of update based on a TVP, see Implementing MERGE Functionality in a Natively Compiled Stored Procedure.

Can subqueries be used in inserts deletes and/or updates?

Subqueries can be nested in the UPDATE , DELETE , INSERT and SELECT data manipulation (DML) statements.


1 Answers

You can try something like

UPDATE  trips
SET     locations = t.city + ', ' + poi.city
FROM    trips t INNER JOIN
        (
            select Distinct city, trip_guid from poi
        ) poi ON t.trip_guid = poi.trip_guid
like image 63
Adriaan Stander Avatar answered Sep 23 '22 15:09

Adriaan Stander