将SQL Server中的主键类型从int更改为uniqueidentifier

8

我需要将表中的主键列从int类型更改为guid类型。数据库已经有数据,我不想丢失数据,并且还需要考虑到外键。有没有无痛的方法可以做到这一点,或者我必须通过一个大脚本手动完成呢?:) 我会感激任何建议。


2
你为什么想要这样做?我目前正在尝试相反的... - cjk
我也会更倾向于建议不要这样做 - 有什么特别的原因吗? - marc_s
我需要这样做是因为我正在设置多个订阅服务器的合并复制,并且我不希望由于同步而更改我的行ID。此外,由于合并复制会自动在所有表中添加GUID列(如果您没有GUID PK列),因此额外的int ID列是多余的。 - anakic
2个回答

7

你需要通过脚本来完成,以下是具体步骤:

0) 进入单用户模式
1) 在主表中添加新的GUID列,并填充数据。
2) 在每个子表中添加新的FK列,并使用UPDATE FROM命令填充。

UPDATE c
    SET FKcolumn=p.NewGuid
    FROM ChildTable             c
        INNER JOIN ParentTable  p ON p.OldIntID=c.OldIntId

3) 删除现有的int FKs
4) 删除旧的int列
5) 在guid列上添加新的FKs
6) 退出单用户模式

您应该能够让SQL Server Management Studio生成用于添加和删除列和键的脚本。只需在SSMS中进行更改,然后单击“生成更改脚本”工具栏图标,即可将代码复制并粘贴到文本文件中。


哇,你真是个天才!! - El7or

1
  1. Use option "Generate scripts" on your database in order to create "DROP/CREATE CONSTRAINT and INDEXES" (use advanced button to tune wizard). Run portion of created SQL script to drop indexes and constraints.
  2. Create one helper function and procedure as follows:

    CREATE FUNCTION [dbo].[GuidFromHash]
    (
        @Input nvarchar(MAX)
    )
    RETURNS nvarchar(MAX)
    AS
    BEGIN
        RETURN LOWER(SUBSTRING(@Input, 1,8)+'-'+SUBSTRING(@Input, 9,4)+'-'+SUBSTRING(@Input, 13,4)+'-'+SUBSTRING(@Input, 17,4)+'-'+SUBSTRING(@Input, 21,12))
    END
    
    CREATE PROCEDURE [dbo].[bigIntToGuid]
    (
        @table varchar(50),
        @column varchar(50)
    )
    AS
    DECLARE @SQL VARCHAR(MAX)
    
    SET @SQL='UPDATE @Table SET @Column=dbo.HashToGuid(''cc''+CONVERT(VARCHAR, HASHBYTES(''MD5'',LTRIM(@Column)),2))'
    SET @SQL=REPLACE(@SQL,'@Table',@Table)
    SET @SQL=REPLACE(@SQL,'@Column',@Column)
    EXEC(@SQL)
    
    SET @SQL='SELECT * FROM @Table'
    SET @SQL=REPLACE(@SQL,'@Table',@Table)
    SET @SQL=REPLACE(@SQL,'@Column',@Column)
    EXEC(@SQL)
    
  3. Now comes the manual work for every table:

    1. Open table in designer (SQL Management Studio or other tool)
    2. Change bigint type of column to VARCHAR(50)
    3. Execute "EXEC bigIntToGuid 'myTable','myBigIntColumn'
    4. Back to table designer change column type to "uniqueidentifier"
    5. Optionally you can add default value: newid(), and/or set column as primary key
  4. Open your sql generated script created in step 1
  5. Select only portion of the script for constraint and index creation, and execute it
这种方法确保将int转换为guid并保持数据完整性。

SQL代码片段中有一个错别字:HashToGuid应该改为GuidFromHash,或者函数名称应该更改为HashToGuid。 - GerardV

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接