Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Invalid column name" error on SQL statement from OpenQuery results

Tags:

I'm trying to perform a SQL query through a linked SSAS server. The initial query works fine:

SELECT "Ugly OLAP name" as "Value" 
FROM OpenQuery( OLAP, 'OLAP Query')

But if I try to add:

WHERE "Value" > 0

I get an error

Invalid column name 'Value'

Any ideas what I might be doing wrong?


So the problem was that the order in which elements of the query are processed are different that the order they are written. According to this source:

http://blogs.x2line.com/al/archive/2007/06/30/3187.aspx

The order of evaluation in MSSQL is:

  1. FROM
  2. ON
  3. JOIN
  4. WHERE
  5. GROUP BY
  6. HAVING
  7. SELECT
  8. ORDER BY

So the alias wasn't processed until after the WHERE and HAVING clauses.

like image 425
dmo Avatar asked Sep 05 '08 17:09

dmo


People also ask

Why does SQL show invalid column name?

An invalid column name error in SQL means that the column name violates the conditions of the column name. If you reference an object that does not exist in the table or the name exists, but you did not reference it correctly, you will get this error.

What does Openquery do in SQL?

The OPENQUERY command is used to initiate an ad-hoc distributed query using a linked-server. It is initiated by specifying OPENQUERY as the table name in the from clause. Essentially, it opens a linked server, then executes a query as if executing from that server.

What is ambiguous error in SQL?

If you run the above query, you will get this error — “Ambiguous name column”. This means two columns have the same column name — that is the “Name” column. The SQL Machine is confused as to which “Name” out of the two tables you are referring to. It is ambiguous — not clear.


2 Answers

This should work:

SELECT A.Value
FROM (
SELECT "Ugly OLAP name" as "Value" 
FROM OpenQuery( OLAP, 'OLAP Query')
) AS a
WHERE a.Value > 0

It's not that Value is a reserved word, the problem is that it's a column alias, not the column name. By making it an inline view, "Value" becomes the column name and can then be used in a where clause.

like image 76
Chris Miller Avatar answered Sep 23 '22 09:09

Chris Miller


You're using "Value" as a column alias, and I don't think the alias can appear in the where clause. It's simply used to name the returned column value. Your where clause should refer to the original column name:

SELECT "Ugly OLAP name" as "Value" 
FROM OpenQuery( OLAP, 'OLAP Query')
WHERE "Ugly OLAP name" > 0
like image 42
Andrew Avatar answered Sep 21 '22 09:09

Andrew