Using SQL Server 2008 R2 (Version 10.50.4000.0):
I have two tables. I want to delete data in one table where an ID exists in another table. Simple enough. However, due to a mistake in typing, I found what appears to be a parser bug.
In the script below, [SomeID] is a column in Table1 but does not actually exist in Table2
Delete from Table1 where [SomeID] in (Select [SomeID] from Table2)
If you run the subquery "Select [SomeID] from Table2, you get an appropriate error message stating that the column does not exist.
If you run the whole delete query though, it runs without error, and deletes everything in table1
It seems that the parser should have caught that the column did not exist in table 2. I know you can use columns from outside the sub-query, and I realize that the parser was assuming that I meant to use a column from table1, but since I had not specified any columns from table2, the parser should have, in my opinion, been smart enough to know there was something wrong. Fortunately, we were in a test environment when this happened. 🙂
Thanks,
Tony
It’s not an error
The engine will do what you put in the query.
when you use
Inclause, it will compare for each row, the field SomeId, with the result in theInFor example, you could do this
So, you could return anything in the select, as a constant, as an Id in the table2, a sum of both, or, like this case, the ID in the first Table.
In this case, when execute the subquery, as doesn’t have a where clause, the subquery will always return a result (unless got no rows), because it doesn’t have a filter, but what will show ? You’re specifying a field in the parent-query, and you’re able to show it, so it will return it.
Of corse, as you’re comparing with In, so is deleting all in table1, right ?