delete语句要注意的BUG.

今天在SQLSERVER 2012中执行下面的SQL语句,发现UserProfile表和UserRole表的数据被全部删掉了,好奇怪。

DELETE FROM [dbo].[UserProfile] WHERE UserId=(select userId from dbo.[user] where username='admin0001')
DELETE FROM [dbo].[UserRole] WHERE UserId=(select userId from dbo.[user] where username='admin0001')
DELETE FROM [dbo].[User] WHERE  username='admin0001' 

 

执行where条件的子查询select userId from dbo.[user] where username='admin0001',报错:Invalid column name 'userId'. 原来User表中叫Id,而不是userId,然而为什么编译器编译通过呢?而且竟然无视后面的where条件,执行不带where条件的。delete from [user]语句。 

 

 
如果是下面的语句 DELETE FROM [dbo].[UserRole] WHERE UserId=(select userId2 from dbo.[user] where username='admin0001') 则执行时候报错。(点击企业管理器中的√,进行语法解析的时候,并不会报错,因为语法只能检查系统关键字,不能检查数据库对象:表和列)
 DELETE2 FROM [dbo].[UserRole] WHERE UserId=(select userId2 from dbo.[user] where username='admin0001') 这样语法检查都不过了。
 
奇怪的是,现在执行之前语句,并不会删除数据了。
反正要注意一点。1. 语法 2.数据逻辑,特别是不会报错,但是很容易混淆的地方。
posted on 2016-01-30 18:20  王老二  阅读(479)  评论(0编辑  收藏  举报