Search code examples
t-sqlinsert-intoopenquery

how to insert results from dynamic openquery into a existing table?


How can I insert the result of below dynamic openquery into an existing table

  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)

I tried Insert into but didn't work.

    INSERT INTO TableA 
    SELECT *
    FROM (EXEC (@TSQL))

Solution

  • You were pretty close

    DECLARE @TSQL varchar(8000), @VAR char(2)
    SELECT  @VAR = 'CA'
    SELECT  @TSQL = 'SELECT * FROM OPENQUERY(MyLinkedServer,''SELECT * FROM pubs.dbo.authors WHERE state = ''''' + @VAR + ''''''')'
    
    INSERT INTO TableA
    EXEC (@TSQL)