Passing Parameters to OPENQUERY in SQL Server
SQL Server's OPENQUERY
statement executes queries on linked servers. However, directly embedding parameters within the OPENQUERY
statement isn't supported. Microsoft's documentation clearly states that OPENQUERY
doesn't accept variables as arguments. Let's explore effective workarounds:
Method 1: Hardcoding Values (for a limited number of parameters)
This approach is suitable when you need to pass only a few specific values. String concatenation is used to build the query:
<code class="language-sql">DECLARE @TSQL varchar(8000), @VAR char(2); SELECT @VAR = 'CA'; SELECT @TSQL = 'SELECT * FROM OPENQUERY(MyLinkedServer,''SELECT * FROM pubs.dbo.authors WHERE state = ''''' + @VAR + ''''''')'; EXEC (@TSQL);</code>
Method 2: Dynamic Query Construction (for more complex queries or dynamic linked server names)
For more intricate queries or scenarios where the linked server name is variable, dynamic SQL offers a solution:
<code class="language-sql">DECLARE @OPENQUERY nvarchar(4000), @TSQL nvarchar(4000), @LinkedServer nvarchar(4000); SET @LinkedServer = 'MyLinkedServer'; SET @OPENQUERY = 'SELECT * FROM OPENQUERY('+ @LinkedServer + ',''''; SET @TSQL = 'SELECT au_lname, au_id FROM pubs..authors'')'; EXEC (@OPENQUERY+@TSQL);</code>
Method 3: Using sp_executesql
(to minimize quoting issues)
To avoid complex string concatenation and potential quoting problems, sp_executesql
provides a cleaner solution:
<code class="language-sql">DECLARE @VAR char(2); SELECT @VAR = 'CA'; EXEC MyLinkedServer.master.dbo.sp_executesql N'SELECT * FROM pubs.dbo.authors WHERE state = @state', N'@state char(2)', @VAR;</code>
These methods offer practical ways to incorporate parameters into your OPENQUERY
statements, enabling efficient interaction with linked servers. Choose the method best suited to your specific needs and complexity.
The above is the detailed content of How Can I Pass Parameters to an OPENQUERY in SQL Server?. For more information, please follow other related articles on the PHP Chinese website!