How to store dynamic query results into a temp table when using EXECUTE() AT linkedserver

Bayne, Lorjust A 1 Reputation point
2022-06-19T19:43:23.227+00:00

I need to query a linked server using OpenQuery () and then store the results into a temp table. I don't have any problems doing this when the query is under the 8000 character limit, but now I have one that exceeds the limit as it is 17,559 characters. So, I have employed the solution shown below and the query runs fine. Now, I need help with how to adjust the script to store the results into a temp table, preferably using Select * Into so I can further manipulate the data.

Declare @strSQL varchar(max)
set @strSQL = N'<your query here>'

exec @strSQL at <YourLinkedServerName>

Thanks
Lorjust

SQL Server Integration Services
SQL Server Integration Services
A Microsoft platform for building enterprise-level data integration and data transformations solutions.
2,628 questions
Windows DHCP
Windows DHCP
Windows: A family of Microsoft operating systems that run across personal computers, tablets, laptops, phones, internet of things devices, self-contained mixed reality headsets, large collaboration screens, and other devices.DHCP: Dynamic Host Configuration Protocol (DHCP). A communications protocol that lets network administrators manage centrally and automate the assignment of Internet Protocol (IP) addresses in an organization's network.
1,044 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,676 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Erland Sommarskog 115.6K Reputation points MVP
    2022-06-19T19:54:34.783+00:00

    You can do:

       CREATE TABLE #temp (...)  
       INSERT TABLE #temp  
           EXEC (@strSQL) at LinkedServer  
    

    Yes, you need to create the table beforehand.

    1 person found this answer helpful.

  2. Limitless Technology 39,786 Reputation points
    2022-06-21T07:33:40.757+00:00

    Hi there,

    If you would like to store dynamic SQL results into # temporary table or a a table variable, you have to declare the DDL first.

    The below article has a sample script that might help you out.
    https://learn.microsoft.com/en-us/answers/questions/257458/how-can-i-insert-dynamic-sql-data-into-temp-table.html

    ------------------------------------------------------------------------------------------------------------------------------

    --If the reply is helpful, please Upvote and Accept it as an answer–

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.