Is there a practical way of migrating from identity columns to hilo keys?

前端 未结 5 1266
面向向阳花
面向向阳花 2021-02-01 08:11

I work with a database that depends heavily on identity columns. However as we have now moved all applications over to NHibernate I wanted to look into using HiLo as seems to be

5条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-01 08:31

    I wrote a script (based of Stephans answer) for fixing hilo values (on sql server) - it assumes that you have a hilo table like

    CREATE TABLE [dbo].[HiloValues](
        [next_hi] [int] NULL,
        [Entity] [varchar](128) NOT NULL
    )
    

    And your table's identity columns are all called ID. Init the Entity table with the table names you want to generate the hilo values for. Running the script will generate a series of update statements like this one:

    UPDATE hv 
    SET next_hi = Transactions.ID/(10 + 1) + 1 
    FROM HiloValues hv 
    CROSS JOIN (SELECT ISNULL(Max(ID), 0) as id FROM Transactions) as Transactions
    WHERE hv.entity = 'Transactions'
    

    Here it is

    DECLARE @scripts TABLE(Script VARCHAR(MAX))
    DECLARE @max_lo VARCHAR(MAX) = '10';
    
    INSERT INTO @scripts
    SELECT '
    UPDATE hv 
    SET next_hi = ' + Entity + '.ID/(' + @max_lo + ' + 1) + 1 
    FROM HiloValues hv 
    CROSS JOIN (SELECT ISNULL(Max(ID), 0) as id FROM ' + entity + ') as ' + entity + '
    WHERE hv.entity = ''' + entity + '''' as script 
    FROM HiloValues WHERE Entity IN (SELECT  name from sys.tables)
    
    
    
    DECLARE curs CURSOR FOR SELECT * FROM @scripts
    DECLARE @script VARCHAR(MAX)
    
    OPEN curs 
    FETCH NEXT FROM curs INTO @script
    
    WHILE @@FETCH_STATUS = 0
    BEGIN
        PRINT @script --OR EXEC(@script)
        FETCH NEXT FROM curs INTO @script
    END
    CLOSE curs
    DEALLOCATE curs
    

提交回复
热议问题