views:

236

answers:

4

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.

+1  A: 

You can use constants and values from the outer select in the sub-select:

Update trips
Set locations = ( Select Distinct trips.city + ', ' + poi.city
                  From poi
                  Where poi.trip_guid = trips.guid )

We don't know how your tables look like, so I can only assume that Distinct will work for you that way (returning only one distinct city in the sub-query).

Peter Lang
The subquery will break if it returns more than 1 record
Jimmie R. Houts
@Jimmie R. Houts: Correct. I was updating my answer the moment you posted your comment, thanks!
Peter Lang
Did you actualy try this, it says **Incorrect syntax near 't'.**
astander
@astander: Thanks for testing, removed the aliases and now it works for me.
Peter Lang
Sorry but its not a solution ;( There are at least 2 cites. The idea is to put all cites in one field.What's why I use the structure like this: SET locations = city + ', ' FROM (select city from poi)
itdebeloper
@itdebeloper: Is there also a `city` field in `trips` or do you just want to concatenate the `city`-fields of `poi` separated by comma?
Peter Lang
I just want to concatenate the city fields of poi.
itdebeloper
@itdebeloper: This sounds quite different than your question. Have a look at this similar question: http://stackoverflow.com/questions/6899/is-there-a-way-to-create-a-mssql-function-to-join-multiple-rows-from-a-subquery
Peter Lang
+2  A: 

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
astander
+1 although I don't agree with formatting - would put the `INNER JOIN` into the next line ;-)
Peter Lang
A: 

Another version.

UPDATE trips
SET locations = trips.city + ', ' + poi.city
FROM trips INNER JOIN poi
ON poi.trip_guid = trips.guid
Martin Smith
A: 

I found the solution - just move the subquery to the UDF :)

UPDATE TRIPS
   SET locations = getAllTripCity(guid);

My UDF's source code:

CREATE FUNCTION dbo.getAllTripCity(
    @tripGuid uniqueidentifier
)
RETURNS nvarchar(200)
AS
BEGIN
 DECLARE @cities nvarchar(200);
 set  @cities = ''
 select @cities =  @cities + city + ' ' from (select DISTINCT city poi where poi.trip_guid = @tripGuid)
 return @ @cities;
END

That's all what you I need to do - works fine :)

itdebeloper