Reputation: 4758
One strange attribute of T-SQL's OPENROWSET()
function is that it cannot accept parameters within the 'query' which it executes remotely. In order to get around this I guess you have to create a long string containing the OPENROWSET
calls and the parametrized query.
Given this limitation, I'm trying to get this piece of code to work:
Declare @DataId int
Declare @RecordType varchar(50)
Declare @Filter varchar(50)
-- ...
SELECT TOP 1
@RecordType = recordType,
@DataId = DataId
FROM OPENROWSET('SQLNCLI',
'Server=MyServer;Trusted_Connection=yes;',
'SELECT recordType, DataId FROM MyDb..data_lookup
WHERE Filter = ''' + @Filter+'''')
This throws an error
Incorrect syntax near '+'
Right now, which makes sense given the restriction on OPENROWSET. But if I convert this to SQL string, won't I lose the ability to set @RecordType
and @DataId
from the results of the query?
Is there any syntactic sugar I can sprinkle on this to get around the restriction and make this work the way I want it to?
Upvotes: 1
Views: 435
Reputation: 4758
Thanks to @Stuart, here is the code that I finally went with:
Declare @DataId int
Declare @RecordType varchar(50)
Declare @Filter varchar(50)
Declare @query nvarchar(4000)
-- ...
select @query = N'select top 1 recordType, DataId
from openrowset(''SQLNCLI'',
''Server=MyServer;Trusted_Connection=yes;'',
''SELECT recordType, DataId from MyDb..data_lookup
where Filter = ''''' + @Filter+''''''')'
declare @t TABLE (recordType varchar(2), DataId int)
insert into @t
exec sp_executeSQL @Query
select top 1 @RecordType = recordType, @DataId = DataId
from @t
Upvotes: 0
Reputation: 12940
Here's some examples of building a string dynamically:
http://support.microsoft.com/kb/314520
You could insert into a table variable first, and then pull your values from there.
DECLARE @t TABLE (DataID int, RecordType varchar(50))
INSERT INTO @t
exec sp_executeSQL N'your OPENROWSERT query'
SELECT TOP 1 @DataID = DataID, @RecordType = RecordType
FROM @t
Upvotes: 1