UPDATE SET 中的子查询 (sql server 2005)
我有一个关于在 Update 语句中使用子查询的问题。我的示例:
UPDATE TRIPS
SET locations = city + ', ' FROM (select Distinct city
from poi
where poi.trip_guid = trips.guid)
是否可以在子查询中引用主表值(trips.guid)?
当我尝试使用 trips.guid
时,出现错误:
“无法绑定多部分标识符“trips.guid”。”
“select Distinct city from poi”子句返回多个城市。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你可以尝试类似的东西
You can try something like
另一个版本。
Another version.
您可以在子选择中使用外部选择中的常量和值:
我们不知道您的表是什么样子,所以我只能假设
Distinct
将以这种方式为您工作(仅返回子查询中的一个不同的城市
)。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).我找到了解决方案 - 只需将子查询移至 UDF :)
我的 UDF 源代码:
这就是你我需要做的 - 工作正常:)
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 :)
我遇到了与最初的海报相同的问题。我的用例如下:
一张表包含体育赛事的日期和时间。因为我从不同的来源获取信息,所以我更改了数据库的架构,因此我有一个代表体育赛事日期的时间和日期时间(或者可能只是日期)的 int 值。
这是我的查询:
一些解释:
您必须为子查询 MatchStartTime 指定一个不同的名称,否则您会从 SQL Server 收到警告/错误。
我还必须添加 MatchId,这样我就知道我正在更新正确的 Match。
SportTypeId 用于分隔数据库中的不同运动项目。
感谢@astander 为我指明了正确的方向。如果没有他的帖子,我会更加努力地最终找到这个解决方案。
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.