简体   繁体   中英

SQL Insert into table stored procedure

I have a code to run stored procedure at the linked server. Want to sync the data from there periodically into my local table. Code itself works well, but "INSERT INTO MyTable" doesn't work with it. How to first create the table from the output and then insert data?

Code itself:

DECLARE @RunSP VARCHAR(1000);
SET @RunSP = 'Declare @errc int, @errm nvarchar(4000); EXEC [Datab1$BI].[dbo].[DataFR] @errc = @errc OUTPUT, @errm = @errm OUTPUT, @DateFrom = N''2021-07-01'', @DateTo = N''2021-07-31'', @StNr = ''2701'', @PNr = ''8270103'';
EXEC (@RunSP) AT [99.88.77.5];

If I make INSERT INTO MyTable that way, it gives an error "Incorrect syntax near the keyword 'SET'."

DECLARE @RunSP VARCHAR(1000);
INSERT INTO MyTable (Columns)
SET @RunSP = 'Declare @errc int, @errm nvarchar(4000); EXEC [Datab1$BI].[dbo].[DataFR] @errc = @errc OUTPUT, @errm = @errm OUTPUT, @DateFrom = N''2021-07-01'', @DateTo = N''2021-07-31'', @StNr = ''2701'', @PNr = ''8270103'';
EXEC (@RunSP) AT [99.88.77.5];

If I declare the procedure and try to insert it, it gives an error message: OLE DB provider "SQLNCLI11" for linked server "10.89.58.4" returned message "The partner transaction manager has disabled its support for remote.network transactions.". The operation could not be performed because OLE DB provider "SQLNCLI11" for linked server "10.89.58.4" was unable to begin a distributed transaction.

DECLARE @RunSP nvarchar(max);
SET @RunSP = N'Declare @errc int, @errm nvarchar(4000); 
    EXEC [Datab1$BI].[dbo].[DataFR] @errc = @errc OUTPUT, @errm = @errm OUTPUT, 
      @DateFrom = N''2021-08-11'', 
      @DateTo = N''2021-08-12'', 
      @StNr = ''2701'', 
      @PNr = ''8270103'';';

DECLARE @exec nvarchar(1024) = N'[99.88.77.5]. 
[Datab1$BI].sys.sp_executesql';

INSERT dbo.MyData(columns) 

EXEC @exec @RunSP;

Linked server properties Data Access, RPC, RPC Out, Enable Promotion of Distributed Transactions for RPC are all 'TRUE'.

Out of ideas, can't find any help googling around as well. Anybody have some ideas to try out?

You shouldn't need dynamic SQL for this:

DECLARE @errc int, @errm nvarchar(4000);

INSERT INTO t
    EXEC [Datab1$BI].[dbo].[DataFR]
        @errc = @errc OUTPUT,
        @errm = @errm OUTPUT,
        @DateFrom = N'2021-07-01',
        @DateTo = N'2021-07-31',
        @StNr = '2701',
        @PNr = '8270103' AT [99.88.77.5];

Here is a rather trivial example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM