Sql-Server

將 openquery 結果插入現有表

  • January 24, 2017

我有一個以這種方式查詢連結 DB2 伺服器的儲存過程:

SET @sql='SELECT * FROM openquery(DB2,''SELECT column1, column2 FROM table'')'
exec sp_executesql @sql

我正在嘗試通過另一個儲存過程將該結果儲存到一個新表中

   INSERT INTO [schema].[Table]
              ([column1]
              ,[column2])
   EXEC('schema.StoredProc')

其中 StoredProc 包含上述 openquery

但是,當我執行第二個儲存過程 (INSERT INTO) 時,輸出視窗會從我的第一個儲存過程中列印出 @sql 的文本,並給我以下消息:

SELECT * FROM openquery(DB2,'SELECT column1, column2 FROM table')
Msg 0, Level 11, State 0, Line 0
A severe error occurred on the current command.  The results, if any, should be discarded.

任何幫助表示讚賞

我會給你一個一直為我工作的例子,它會給你一個想法:

DECLARE @Radhe  TABLE(
   [n] [bigint] NOT NULL,
   [Login_Name] [nvarchar](128) NOT NULL,
   [Login_From] [nvarchar](128) NULL,
   [Account_Type] [nvarchar](128) NULL,
   THE_ORDER INT NOT NULL
   PRIMARY KEY CLUSTERED (Login_Name,N)
)



       SELECT @SQL = 'SELECT 
                       [n],
                       [Login_Name],
                       [Login_From],
                       [Account_Type],
                       the_order       
                     FROM OPENQUERY(' + quotename(@SERVER ) + ',' + '''' + 'SET FMTONLY OFF; exec sp_GetServerLogins ' + '''' + ')'

       INSERT INTO @Radhe
       exec ( @sql)

引用自:https://dba.stackexchange.com/questions/162060