Change datatype of column to uniqueidentifier from bigint
You cannot convert from an integer to a uniqueidentifier
. But you can do it like this.
First delete old data from the table.
Alter the column to some text-format (such as
VARCHAR(200)
).ALTER TABLE dbo.tbltest ALTER COLUMN ID VARCHAR(200)
- Now again
ALTER TABLE dbo.tbltest ALTER COLUMN ID uniqueidentifier
To be clear, you can't convert a column from numeric to uniqueidentifier
directly, but you can convert numeric
to varchar
to uniqueidentifier
.
Note to people using Entity Framework:
Obviously, if you have a large database with complex relationships, dropping all relationships and ID columns, and re-adding them is a huge ordeal.
It's much easier to update the generated model (.edmx).
Yes, Visual Studio allows you to update the data type without complaining. In fact, when you save the .edmx file, the relationships will be validated; any fields that you may have missed will show up as errors.
After you're finished, you can regenerate the database from the model. Boom, done.
You need to add the column first (possibly with a default or nullable so that the column can be successfully added to rows with existing data), update it to the values you want or need, change any keys (if it is a primary key change it to the new column and then also change any foreign keys to this table), then remove the old column and alter the new column as necessary (e.g. setting identity seed, removing nullable, etc.).