I'm trying to declare connection as a variable and use it in a query:
DECLARE @connStr VARCHAR(MAX) = 'server=xxxxx'
DECLARE @table VARCHAR(MAX) = 'xxxxx'
BEGIN
DELETE FROM @table;
INSERT @table
SELECT * FROM OPENROWSET(
'SQLNCLI',
@connStr,
'SELECT TOP 10 * from xxxx ORDER BY xxxx DESC'
);
END;
And it results in syntax error.
What's wrong with @connStr? I'm using SQLServer 2012
OPENROWSETdoes not support variables, period. Only string literals. Doing anything dynamic withOPENROWSETrequires dynamic SQL.exec?@Tableis also intended to be a variable holding a table name (which will not work either). In that case, you are much, much better off doing this client-side, as T-SQL does not like dynamic result sets, and having multiple levels of escaping is no picnic either.@tableis supposed to represent a dynamic table's name, why is is avarchar(MAX)? An object name can be at most 128 characters long, not 2Billion...