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.
I had the same issue as the initial poster. My use case was the following: One table contained Date and Time of a sport event. Because I am getting information from different sources, I changed the schema of the database so I had a int value for time and datetime (or maybe just date) for the date of the sport event.
This is my query:
Some explanation: You have to give the subquery MatchStartTime a different name otherwise you get a warning/error from SQL Server. I also had to add MatchId so I knew I was updating the correct Match. The SportTypeId is used to separate different sports in the database.
Thanks to @astander for pointing me in the right direction. Without his post I would have struggled a bit more to end up with this solution.
I found the solution - just move the subquery to the UDF :)
My UDF's source code:
That's all what you I need to do - works fine :)
You can use constants and values from the outer select in the sub-select:
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 distinctcity
in the sub-query).You can try something like
Another version.