SQL Server how to drop identity from a column

前端 未结 3 1725
予麋鹿
予麋鹿 2020-12-08 01:18

Is there an easy way to remove an identity from a table in SQL Server 2005?

When I use Management Studio, it generates a script that creates a mirror table without

3条回答
  •  北海茫月
    2020-12-08 02:07

    If you are on SQL Server 2005 or later, you can do this as a simple metadata change (NB: doesn't require an edition supporting partitioning as I originally stated).

    Example code pilfered shamelessly from the workaround by Paul White on this Microsoft Connect Item.

    USE tempdb;
    GO
    -- A table with an identity column
    CREATE TABLE dbo.Source 
    (row_id INTEGER IDENTITY PRIMARY KEY NOT NULL, data SQL_VARIANT NULL);
    GO
    -- Some sample data
    INSERT dbo.Source (data)
    VALUES (CONVERT(SQL_VARIANT, 4)),
            (CONVERT(SQL_VARIANT, 'X')),
            (CONVERT(SQL_VARIANT, {d '2009-11-07'})),
            (CONVERT(SQL_VARIANT, N'áéíóú'));
    GO
    -- Remove the identity property
    BEGIN TRY;
        -- All or nothing
        BEGIN TRANSACTION;
    
        -- A table with the same structure as the one with the identity column,
        -- but without the identity property
        CREATE TABLE dbo.Destination 
        (row_id INTEGER PRIMARY KEY NOT NULL, data SQL_VARIANT NULL);
    
        -- Metadata switch
        ALTER TABLE dbo.Source SWITCH TO dbo.Destination;
    
        -- Drop the old object, which now contains no data
        DROP TABLE dbo.Source;
    
        -- Rename the new object to make it look like the old one
        EXECUTE sp_rename N'dbo.Destination', N'Source', 'OBJECT';
    
        -- Success
        COMMIT TRANSACTION;
    END TRY
    BEGIN CATCH
        -- Bugger!
        IF XACT_STATE() <> 0 ROLLBACK TRANSACTION;
        PRINT ERROR_MESSAGE();
    END CATCH;
    GO
    
    -- Test the the identity property has indeed gone
    INSERT dbo.Source (row_id, data)
    VALUES (5, CONVERT(SQL_VARIANT, N'This works!'))
    
    SELECT row_id,
            data
    FROM    dbo.Source;
    GO
    
    -- Tidy up
    DROP TABLE dbo.Source;
    

提交回复
热议问题