0

Can someone give me a working example of using OPENROWSET on SQL Server with dynamic SQL (sp_executesql) executing a stored procedure with two parameters as variables, preferably date and integer? I want to use that output and INSERT INTO a temp table

INSERT INTO #t
SELECT * FROM OPENROWSET
(
    SQL Server
    SP with two parameters date and integer)
   
SELECT * FROM #t
1
  • 1
    Why not use a Linked Server? Then just a normal INSERT ... EXEC LinkedServer.Db.Schema.Proc ... Commented Mar 7 at 3:33

1 Answer 1

1

This is a job for dynamic SQL. You can find extensive coverage here and here.

DECLARE @sql    nvarchar(MAX),  
        @params nvarchar(4000)

SELECT @params = N'@YourDate    date, 
                   @YourInt     int'

SELECT @sql = 
    'INSERT INTO #t
        SELECT *
        FROM OPENROWSET(
            ''Provided Name, e.g. SQLNCLI'',
            ''Provided String e.g. Server=Seattle1;Trusted_Connection=yes;'',
            ''EXEC YourProcedure @YourDate, @YourInt'')'

PRINT @SQL
EXEC sp_executesql @sql, @params, @YourDate = '20220101', @YourInt = 12345

SELECT * FROM #t

This dbfiddle shows that the PRINT's output looks correct, but I must admit that I don't have the right setup on my end to actually test the EXEC.

7
  • You cannot parametrise an OPENROWSET query like that. Whatever @name sequences the query argument of OPENROWSET may contain cannot be processed as arguments by sp_executesql, because they are inside a string literal as far as sp_executesql is concerned. You will have to concatenate the actual values into the query as literals: SET @sql = '…OPENROWSET(…, ''EXEC YourProcedure ' + … /* expression for the first argument, appropriately quoted if necessary */ + ', ' + … /* second argument, appropriately quoted if necessary */ + ''')'; PRINT @sql; INSERT INTO #t EXEC sp_executesql @sql; ….
    – Andriy M
    Commented Mar 7 at 4:34
  • @AndriyM Oh. You're right. It's just the EXEC line that needs to change, right?
    – J. Mini
    Commented Mar 7 at 8:05
  • The EXEC line inside the OPENROWSET needs to be built dynamically, yes. The EXEC sp_executesql line needs to lose the arguments after the @sql as well.
    – Andriy M
    Commented Mar 7 at 10:56
  • @AndriyM Like this? This is awful.
    – J. Mini
    Commented Mar 7 at 20:19
  • The one given in the above link to the dbfiddle.uk/bnug4_RH site runs fine if just print is used. If EXEC @SQL is run, it throws an error saying unclosed quotation mark after the charcter string 'Exec .....'
    – mk SQL
    Commented Mar 8 at 19:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.