I have found the following issue in SQL Server 2008 Management Studio. When I run the following script as whole I expect errors (due to a “copy and paste error”), but don’t receive them.
IF OBJECT_ID('Foo') IS NOT NULL
BEGIN
DROP TABLE Foo
END
IF OBJECT_ID('Bar') IS NOT NULL
BEGIN
DROP TABLE Bar
END
CREATE TABLE Foo (
FooID int
)
Create Table Bar (
BarID int
, FooID int
)
INSERT INTO Foo
SELECT 1 UNION ALL SELECT 2
INSERT INTO Bar
SELECT 1,1 UNION ALL SELECT 2,1 UNION ALL SELECT 3,1
GO
IF OBJECT_ID('tempdb..#temp') IS NOT NULL
BEGIN
DROP TABLE #TEMP
END
GO
CREATE TABLE #TEMP (
FooID int
)
INSERT INTO #TEMP
SELECT FooID FROM Bar
GO
SELECT * FROM Foo WHERE FooID IN (SELECT FooID FROM #TEMP)
GO
SELECT * FROM Bar WHERE BarID IN (SELECT BarID FROM #TEMP)
GO
SELECT * FROM #TEMP
GO
The second last statement containing the where clause filter on “SELECT BarID FROM #TEMP” runs, but there is no BarID column in #TEMP. When running the script as a whole I receive no error and the script return all rows in Foo. However when I run the command on its own then I get the error informing me that there is no BarId in #TEMP.
Is there a reason for this? Is it my code?
Your second to last query actually is working correctly.
Other commenters please correct me, but I understand this to be a correlated subquery. Table aliasing will show what is actually going on. Your query is equivalent to this:
For each row in #TEMP, the nested select is actually returning the current value of BarID from table Bar, so yes, BarID in (BarID) is true, so every row in Bar is matched, so every row is returned.
To show that you’re not crazy, try
This raises the error I think you’re expecting.