当IDENTITY_INSERT设置为OFF时,无法在表'TBL_AT_INOUT'中为标识列插入显式值

时间:2017-12-08 13:31:11

标签: sql-server

Insert into HWT FINAL. DO. TBL_AT_INOUT
(ID)
SELECT ID FROM TBL_AT_INOUT_20171208
WHERE ID=904017

执行时出错

1 个答案:

答案 0 :(得分:0)

这就是你要找的东西:

IF object_id(N'tempdb..#test_table_01', N'U') IS NOT NULL
    DROP TABLE #test_table_01;

go

CREATE TABLE #test_table_01
  (
       [id]     INT IDENTITY(1, 1)
       , [name] SYSNAME
  );

--
-- fail method
-------------------------------------------------
BEGIN
    BEGIN try
        INSERT INTO #test_table_01
                    ([id]
                     , [name])
        VALUES      (1,N'Lucy');
    END try
    BEGIN catch
        SELECT N'This throws an error' AS [result]
               , ERROR_MESSAGE()       AS [error_message];
    END catch;

    SELECT N'No records were inserted' AS [note]
           , [id]
           , [name]
    FROM   #test_table_01;
END;


--
-- success method
-------------------------------------------------
BEGIN
    BEGIN try
        SET IDENTITY_INSERT #test_table_01 ON;

        INSERT INTO #test_table_01
                    ([id]
                     , [name])
        VALUES      (1,N'Lucy');

        -- 
        -- REMEMBER TO SET IDENTITY_INSERT BACK OFF!!!
        SET IDENTITY_INSERT #test_table_01 OFF;
    END try
    BEGIN catch
        SELECT N'This allows the insert' AS [result]
               , ERROR_MESSAGE()         AS [error_message];
    END catch;

    SELECT N'Records were inserted as desired!' AS [note]
           , [id]
           , [name]
    FROM   #test_table_01;
END;