Getting syntax error when trying to use OPENQUERY

NA Slacker picture NA Slacker · Oct 5, 2010 · Viewed 9.4k times · Source

I am trying to do a query via ODBC to our ERP database. The documentation guide suggests that we use OPENQUERY to send the query.

Here is my example query

SELECT
 Q.Part_No,
 Q.[Description],
 Q.Part_Type
FROM OPENQUERY
(
 LINKEDSERVER,
 '
 SELECT
  P.Part_No,
  P.[Description],
  P.Part_Type
 FROM LINKEDSERVER...Part_V_Part AS P
 WHERE P.Part_No = ''2712768''
 '
) AS Q

When I try to run that query though I get the following error

OLE DB provider "MSDASQL" for linked server "LINKEDSERVER" returned message "[LINKED][ODBC Plex ODBC Report Data Source driver][OpenAccess SDK SQL Engine]Syntax error in SQL statement. syntax error line 1 at or after token <LINKEDSERVER>.[0]".
Msg 7321, Level 16, State 2, Line 1
An error occurred while preparing the query "
 SELECT
  P.Part_No,
  P.[Description],
  P.Part_Type
 FROM LINKEDSERVER...Part_V_Part AS P
 WHERE P.Part_No = '2712768'
 " for execution against OLE DB provider "MSDASQL" for linked server "LINKEDSERVER".

Can anyone help me here? I've never used OPENQUERY before, but I'm coping the example straight as it is in the example documentation.

Answer

SQLMenace picture SQLMenace · Oct 5, 2010

Should be like this

    SELECT
 Q.Part_No,
 Q.[Description],
 Q.Part_Type
FROM OPENQUERY
(
 LINKEDSERVER,
 '
 SELECT
  P.Part_No,
  P.[Description],
  P.Part_Type
 FROM DatabaseName.SchemaName.Part_V_Part AS P
 WHERE P.Part_No = ''2712768''
 '
) AS Q

Replace DatabaseName and SchemaName with your actual database name and schemaname (probably dbo)

You don't need the linked server name inside the query

Take a look at Having Fun With OPENQUERY And Update,Delete And Insert Statements for some examples