Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WHERE clause using OPENQUERY with linked server

I connect with MS SQL Server Express 2012 a Database via ODBC.

My query:

Select * from openquery(test,'SELECT * FROM Versuchsanlage_DB WHERE value =27')

SQL QUERY

But this query

 Select * from openquery(test,
   'SELECT * FROM Versuchsanlage_DB 
    WHERE identifier = AGENT.OBJECTS.Versuchsanlage.Variable_1_Byte')

OR

Select * from openquery(test,
   'SELECT * FROM Versuchsanlage_DB
    WHERE identifier = Variable_1_Byte')

doesn't work. Why?

like image 269
M1NT Avatar asked Dec 12 '13 14:12

M1NT


People also ask

Is Openquery faster than linked server?

The OPENQUERY is faster than the linked server because when we use the linked server, the SQL Server breaks the query into local and remote queries. The local queries are executed on the local server, and remote queries will be sent to the remote server.

How does Openquery work in SQL Server?

Executes the specified pass-through query on the specified linked server. This server is an OLE DB data source. OPENQUERY can be referenced in the FROM clause of a query as if it were a table name. OPENQUERY can also be referenced as the target table of an INSERT, UPDATE, or DELETE statement.

How do I query a linked database in SQL Server?

1 Open SQL Server Management Studio, navigate to the Object Explorer pane, and select Server Objects > Linked servers > Providers. 2 Right-click mrOledb. Provider and select Properties. 3 Select allow in process, and then click OK.


1 Answers

You're searching for a string value in the identifier column. Strings must be enclosed in quotes. Since the select statement is being passed to OPENQUERY as a string, quotes inside that string must be escaped:

Select * from openquery(test,
   'SELECT * FROM Versuchsanlage_DB 
    WHERE identifier = ''AGENT.OBJECTS.Versuchsanlage.Variable_1_Byte''')

OR

Select * from openquery(test,
       "SELECT * FROM Versuchsanlage_DB 
        WHERE identifier = 'AGENT.OBJECTS.Versuchsanlage.Variable_1_Byte'")

These queries are functionally the same, one just uses all single-quotes while the other uses double-quotes. Pick whichever you think is easier to read.

Alternatively you could drop OPENQUERY and use EXECUTE...AT syntax for parameterization (this requires RPC to be enabled for the linked server):

EXECUTE('SELECT * FROM Versuchsanlage_DB WHERE identifier = ?',
        'AGENT.OBJECTS.Versuchsanlage.Variable_1_Byte') AT [test];
like image 137
Bryan Avatar answered Sep 30 '22 16:09

Bryan