Search code examples
sql-servert-sqlsql-server-2008-r2openrowset

How can I get data back from a dynamic call to OPENROWSET?


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?


Solution

  • 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