I have a question about using subqueries 开发者_如何学Pythonin 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.
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
Another version.
UPDATE trips
SET locations = trips.city + ', ' + poi.city
FROM trips INNER JOIN poi
ON poi.trip_guid = trips.guid
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).
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 :)
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:
UPDATE Matches
SET StartTime= MatchTime.ThisMatchStartTime
FROM Matches AS M
INNER JOIN (SELECT CONVERT(int, CONVERT(varchar, DATEPART(Hour, MatchDate)) + RIGHT('00' + CONVERT(varchar, DATEPART(Minute, MatchDate)),2)) AS ThisMatchStartTime, MatchId
FROM [Matches]
WHERE SportTypeId=16) AS MatchTime ON M.MatchId=MatchTime.MatchId
WHERE StartTime > 2400
AND SportTypeId = 16;
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.
精彩评论