OPENROWSET does not accept variables for its arguments (SQL Server)

If you’re trying to use OPENROWSET to run an ad hoc distributed query in SQL Server, but you keep getting an “incorrect syntax” error, and you just can’t see anything wrong with your syntax, it could be that you’re trying to use a variable for one of the arguments.

As mentioned in the title of this post, OPENROWSET does not accept variables for its arguments.

If you’re using variables as arguments, try changing these to string literals.

Example

Here’s an example to demonstrate.

DECLARE @tsql varchar(500);
SET @tsql = 'SELECT * FROM Test.dbo.Cats';
SELECT * FROM OPENROWSET(
    'SQLNCLI', 
    'Server=MyLinkedServer;Trusted_Connection=yes;', 
    @tsql);

Result:

Msg 102, Level 15, State 1, Line 16
Incorrect syntax near '@tsql'.

If you check the Microsoft documentation, you can see that it explicitly states that:

OPENROWSET does not accept variables for its arguments.

So if we change the above code so that all arguments are string literals, we no longer get an error.

SELECT * FROM OPENROWSET(
    'SQLNCLI', 
    'Server=MyLinkedServer;Trusted_Connection=yes;', 
    'SELECT * FROM Test.dbo.Cats');

Result:

+---------+-------------+
| CatId   | CatName     |
|---------+-------------|
| 1       | Meow        |
| 2       | Fluffy      |
| 3       | Scratch     |
| 4       | Bulldog     |
| 5       | King George |
| 6       | Sharp       |
| 7       | Fritz       |
| 8       | Garfield    |
| 9       | Boss        |
+---------+-------------+