[英]sql server 2008 management studio not checking the syntax of my query
As always, there will be a reasonable explanation for my surprise, but till then....和往常一样,对我的惊讶会有一个合理的解释,但在那之前......
I have this query我有这个查询
delete from Photo where hs_id in (select hs_id from HotelSupplier where id = 142)
which executes just fine (later i found out that the entire photo table was empty)执行得很好(后来我发现整个照片表都是空的)
but the strange thing: there is no field hs_id
in HotelSupplier, it is called hs_key
!但奇怪的是: hs_id
中没有字段 hs_id ,它被称为hs_key
!
So when i execute the last part所以当我执行最后一部分时
select hs_id from HotelSupplier where id = 142
separately (select that part of the query with the mouse and hit F5), i get an error, but when i use it in the in
clause, it doesn't!单独(用鼠标选择查询的那部分并按 F5),我收到一个错误,但是当我在in
子句中使用它时,它没有!
I wonder if this is normal behaviour?我想知道这是否是正常行为?
It is taking the value of hs_id
from the outer query.它从外部查询中hs_id
的值。
It is perfectly valid to have a query that doesn't project any columns from the selected table in its select
list.查询不从其select
列表中的选定表中投影任何列是完全有效的。
For example例如
select 10 from HotelSupplier where id = 142
would return a result set with as many rows as matched the where
clause and the value 10
for all rows.将返回一个结果集,其中包含与where
子句匹配的行数和所有行的值10
。
Unqualified column references are resolved from the closest scope outwards so this just gets treated as a correlated sub query.不合格的列引用从最近的范围向外解析,因此这只是被视为相关的子查询。
The result of this query will be to delete all rows from Photo
where hs_id
is not null as long as HotelSupplier has at least one row where id = 142 (and so the subquery returns at least one row)此查询的结果将是删除Photo
中hs_id
不为空的所有行,只要 HotelSupplier 至少有一行 id = 142(因此子查询至少返回一行)
It might be a bit clearer if you consider what the effect of this is如果你考虑一下它的效果可能会更清楚一些
delete from Photo where Photo.hs_id in (select Photo.hs_id)
This is of course equivalent to这当然相当于
delete from Photo where Photo.hs_id = Photo.hs_id
By the way this is far and away the most common "bug" that I personally have seen erroneously reported on Microsoft Connect.顺便说一下,这是我个人在 Microsoft Connect 上错误报告的最常见的“错误”。 Erland Sommarskog includes it in his wishlist for SET STRICT_CHECKS ON
Erland Sommarskog 将其包含在他的SET STRICT_CHECKS ON
愿望清单中
It's a strong argument for keeping column names consistent between tables.这是保持表之间列名一致的有力论据。 As @Martin says, the SQL syntax allows column names to be resolved from the outer query, when there's no match in the inner query.正如@Martin 所说,当内部查询中没有匹配项时,SQL 语法允许从外部查询解析列名。 This is a boon when writing correlated subqueries, but can trip you up sometimes (as here)这在编写相关子查询时是一个福音,但有时会绊倒你(如这里)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.