Using parameters in OPENQUERY
OPENQUERY is a powerful tool for accessing linked server data, but incorporating parameters into queries can be challenging. The documentation clearly states that OPENQUERY does not accept variables for its parameters.
Solution:
To overcome this limitation, several workarounds are available:
<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>
<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>
<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>
The above is the detailed content of How Can I Use Parameters with OPENQUERY in SQL Server?. For more information, please follow other related articles on the PHP Chinese website!