I need to change the type of my primary key column on a table from int to guid. The database already has data that I don't want to lose, and there are foreign keys to consider. Is there a painless way to do this or do I have to manually do it through a big a** script?:) I would appreciate any suggestions
You'll have to do it the hard way, using scripts:
0) get in single user mode
1) add the new GUID column to the main table, and populate it.
2) add the new FK column to each child table and populate them with an UPDATE FROM
UPDATE c
SET FKcolumn=p.NewGuid
FROM ChildTable c
INNER JOIN ParentTable p ON p.OldIntID=c.OldIntId
3) drop the existing int FKs
4) drop the old int columns
5) add the new FKs on the guid column
6) get out of single user mode
you should be able to get SQL Server Management studio to generate the scripts for adding and dropping the columns and keys. Just make the changes in SSMS and click on the "Generate Change Script" toolbar icon and you can cut and paste the code to a text file.
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)
Now comes the manual work for every table:
This approach ensures converting int to guid and keep data integrity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With