Setting Identity to on or off in SQL server

后端 未结 6 731
日久生厌
日久生厌 2021-02-12 18:26

I want to set Is Identity property of a column to off and after inserting an explicit value setting it to on again.I\'ve written this query :

SET IDENTITY_INSERT         


        
6条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-12 18:56

    You can turn off the Identity property, but it involves editing system tables which is not considered a good practice. You are also unlikely to have the necessary rights, and will probably see You do not have permission to run the RECONFIGURE statement attempting the following code:

    DECLARE @tableName nvarchar(128) = 'YourTable';
    
    -- Get a list of identity columns (informational)
    SELECT OBJECT_NAME(object_id) tableName, sc.name colName, st.name dataType
    FROM sys.columns sc
    JOIN sys.types st
        ON st.system_type_id = sc.system_type_id
    WHERE sc.is_identity = 1
    AND OBJECT_NAME(object_id) = @tableName
    
    -- Allow ad-hoc changes to system catalogs
    EXEC  sp_configure 'allow update', 1
    GO
    reconfigure with override
    GO
    -- Eliminate the identityness
    UPDATE syscolumns SET colstat = colstat - 1
    WHERE id = object_id(@tableName)
    AND name = 'Id' -- Specify column if you like, though only one identity per table is currently supported
    GO
    -- Unallow ad-hoc changes to system catalogs
    exec sp_configure 'allow update', 0
    GO
    reconfigure with override
    GO
    

提交回复
热议问题