Inserted Id in linked SQL Server

末鹿安然 提交于 2020-04-30 17:02:42

问题


I have linked together 2 Microsoft SQL servers, let's call them LinkedServer1 and Server2. I am trying to insert data from the second one using an INSERT script with OUTPUT to obtain the auto-incremented id:

DECLARE @newIdHolderTable TABLE (Id INT)

INSERT INTO [LinkedServer1].[Db1].[dbo].[Table1]
  (Field1
  ,Field2)
OUTPUT inserted.ID INTO @newIdHolderTable 
SELECT 
    Field1
   ,Field2
FROM [Server2].[Db1].[dbo].[Table1]
WHERE [Id] = @Id

Unfortunately this fails with an error message:

A remote table cannot be used as a DML target in a statement which includes an OUTPUT clause or a nested DML statement.

How can I insert values into a linked SQL server table and obtain the new Id?


回答1:


If your linked server Server2 is visible from LinkedServer1, you can do this:

declare @newIdHolderTable table (Id INT);

declare @stmt nvarchar(max)

select @stmt = '
  INSERT [Db1].[dbo].[Table1] (Field1,Field2) VALUES (values);
  OUTPUT inserted.ID
  SELECT 
      Field1
     ,Field2
  FROM [Server2].[Db1].[dbo].[Table1]
  WHERE [Id] = @Id
'

insert into @newIdHolderTable
exec LinkedServer1.master..sp_executesql
    @stmt = @stmt,
    @params = N'@Id int',
    @Id = @Id


来源:https://stackoverflow.com/questions/18981229/inserted-id-in-linked-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!