SQL Server – Alternatives to Linked Servers for Inline SQL with Parameters

linked-serverparameterselectsql server

I am trying to find a solution to execute inline SQL with parameters against some linked server databases. From what I have found online the only proper way to query a linked server is to use OPENQUERY. And the only proper way to prevent SQL injection is with parameters.

However, the way OPENQUERY is structured it does not look like parameters are possible. Am I right to assume the only proper way to query with this type of configuration is with stored procedures? Are there any alternatives? Are there any similar database configuration that could be used?

Any thoughts or advice on the subject would be greatly appreciated.

Best Answer

No, you shouldn't use OPENQUERY IMHO. How about this construct, which allows you to use sp_executesql and parameters:

DECLARE @someParam INT = 5;

EXEC LinkedServerName.master.sys.sp_executesql
  @stmt = N'SELECT @i, @@SERVERNAME, @@VERSION;', 
  @params = N'@i INT', @i = @someParam;