0

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?

Germstorm
  • 9,709
  • 14
  • 67
  • 83

1 Answers1

2

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
Roman Pekar
  • 107,110
  • 28
  • 195
  • 197