这个
(2009-05-07 09:09)
以前写过的
一个帖子,现转回这里,做个备份
1. 创建表a
create table a(
id int identity(1,1),
a int
)
declare @i int
set @i = 0
while @i<100
begin
insert a(a) select @i+1
set @i=@i+1
end
2.创建表b
create table b (
b int
)
insert b(b) values(1)
3.以下语句是一个错误语句,原意是删除表a中id存在于表b中b字段的记录。应该是
delete a where id in (select b from b)
但一不小心写错了,写成:delete a where id in (select id from b)
4.如果你认为应该有出错提示,那你就错了。你会发现执行成功,以及a表中所有的数据都被删除了。
可惜发到Microsoft Connect并没有人回应这个问题!
终于等到Microsoft的回复
Hi,
The behavior you are seeing is by design. In the correlated subquery, if you do not qualify column references we will first try to bind the columns to the FROM clause in the subquery and if that fails we will try to bind to the FROM clause in the outer query. This is also according to ANSI SQL specifications and works pretty much the same in other database systems too. You have to use table aliases to write queries that doesn't result in such ambiguous behavior. See the KB article below for more details.
http://support.microsoft.com/kb/298674
--
Umachandar, SQL Programmability Team
由 Microsoft 在 2009/5/8 10:54 发送
create table a(
id int identity(1,1),
a int
)
declare @i int
set @i = 0
while @i<100
begin
insert a(a) select @i+1
set @i=@i+1
end
2.创建表b
create table b (
b int
)
insert b(b) values(1)
3.以下语句是一个错误语句,原意是删除表a中id存在于表b中b字段的记录。应该是
delete a where id in (select b from b)
但一不小心写错了,写成:delete a where id in (select id from b)
4.如果你认为应该有出错提示,那你就错了。你会发现执行成功,以及a表中所有的数据都被删除了。
可惜发到Microsoft Connect并没有人回应这个问题!
终于等到Microsoft的回复
Hi,
The behavior you are seeing is by design. In the correlated subquery, if you do not qualify column references we will first try to bind the columns to the FROM clause in the subquery and if that fails we will try to bind to the FROM clause in the outer query. This is also according to ANSI SQL specifications and works pretty much the same in other database systems too. You have to use table aliases to write queries that doesn't result in such ambiguous behavior. See the KB article below for more details.
http://support.microsoft.com/kb/298674
--
Umachandar, SQL Programmability Team
由 Microsoft 在 2009/5/8 10:54 发送