【问题标题】:Cannot insert into identity column of linked server无法插入链接服务器的标识列
【发布时间】:2020-12-31 17:13:10
【问题描述】:

即使我将 IDENTITY_INSERT 设置为 ON 并指定列,插入链接服务器时仍然会出错。

直接在服务器上时:

CREATE TABLE InsertTest (
    PrimaryAutoKey int NOT NULL
        IDENTITY(1, 1) PRIMARY KEY,
    ID nvarchar(10) NOT NULL,
    Description nvarchar(50)
)

INSERT INTO InsertTest(ID, Description)
VALUES ('Test01', 'First record; key auto-assigned')

SET IDENTITY_INSERT InsertTest ON

INSERT INTO InsertTest(PrimaryAutoKey, ID, Description)
VALUES (10, 'Test10', 'Second record; key specified')

SELECT * FROM InsertTest
/*
PrimaryAutoKey ID         Description
-------------- ---------- --------------------------------------------------
1              Test01     First record; key auto-assigned
10             Test10     Second record; key specified
*/

到目前为止一切顺利。但是,当我从将其作为链接服务器的远程服务器发出以下命令时

INSERT INTO [LinkedServer].[DB].[dbo].InsertTest(PrimaryAutoKey, ID, Description)
VALUES (3, 'Test03', 'Third record; key specified')

我得到错误:

OLE DB provider "MSOLEDBSQL" for linked server "LinkedServer" returned message "Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done.".
Msg 7344, Level 16, State 1, Line 10
The OLE DB provider "MSOLEDBSQL" for linked server "LinkedServer" could not INSERT INTO table "[LinkedServer].[DB].[dbo].[InsertTest]" because of column "PrimaryAutoKey". The user did not have permission to write to the column.

我正在使用 sa 上下文连接到链接服务器,并且都允许 RPC IN/OUT。

【问题讨论】:

    标签: sql-server linked-server identity-insert


    【解决方案1】:

    将整个批次发送到链接服务器并在那里运行。

    例如

    declare @sql nvarchar(max) = N'
    
    INSERT INTO InsertTest(ID, Description)
    VALUES (''Test01'', ''First record; key auto-assigned'')
    
    SET IDENTITY_INSERT InsertTest ON
    
    INSERT INTO InsertTest(PrimaryAutoKey, ID, Description)
    VALUES (10, ''Test10'', ''Second record; key specified'')
    
    '
    
    exec (@sql) at LinkedServer
    

    【讨论】:

    • 这解决了它。它还暴露了另一个问题:SET IDENTITY_INSERT tablename ON 语句是 connection specific 并且必须在插入之前从客户端连接发出。我将它设置在服务器上,错误地认为它会在所有连接中保持设置为 ON,直到设置为 OFF。
    猜你喜欢
    • 2011-08-08
    • 2012-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 2015-10-27
    相关资源
    最近更新 更多