I am submitting the following query in Sql Server (2008)
WITH query AS (SELECT TOP 100 PERCENT
ROW_NUMBER() OVER
(ORDER BY [tbl2].[col2] ASC) AS TableRowNumber ,
[tbl1].[col1] ,
[tbl2].[col2]
FROM [db1].[dbo].[tbl1] AS [tbl1]
JOIN [db2].[dbo].[tbl2] AS [tbl2]
ON [tbl1].[id] = [tbl2].[id])
SELECT
*
FROM query
WHERE TableRowNumber BETWEEN 1 AND 15
ORDER BY TableRowNumber ASC
When this query is run, it returns the following error message:
Msg 207, Level 16, State 1, Line 3
Invalid column name 'col2'.
The sql join itself runs fine (when run as a normal query. The issue seems to be with using the Row_Number() over (Order By COLUMN) when COLUMN is in a different database from the FROM table of the query.
If I would change line 3 to read (Order By [tbl1].[col1] ASC) then it runs without any issues. The error only happens when the sort column is in a different DB.
Does anyone know why this is happening? Any suggestions on how to fix this?
This works for me no problem:
So I suspect there is some other issue going on (e.g.
col2really doesn’t exist). Also I noticed that you are calling the thingtb2andtbl2– is it possible you have both atb2and atbl2in the other database, and you’re referencing the wrong one?EDIT I created this:
Then ran your query in the context of
db1. It ran fine. So for the last time I will suggest that there is something you’re not telling us about the schema, or perhaps the fact that you’ve obfuscated the names (and already had to correct one typo from doing so) has obfuscated something too much even for you…