Change datatype of column to uniqueidentifier from bigint

后端 未结 5 1043
遇见更好的自我
遇见更好的自我 2021-01-01 19:05

I want to change the datatype of a column in a table in sql server. I used the following statement:

ALTER TABLE dbo.tbltest  
ALTER COLUMN ID uniqueidentifie         


        
5条回答
  •  忘掉有多难
    2021-01-01 20:01

    I disagree with the other answers that state that this can't be done without dropping data. In fact @Lucero has already eluded to the correct way to do this in his comment.

    You most certainly can convert a BigInt to a UniqueIdentifier (and back again if you wish.) You DO NOT need to drop the table, truncate the data, or do anything more radical then run a few commands. It takes two steps:

    ALTER TABLE dbo.tbltest ALTER COLUMN [ID] VARBINARY(8)
    ALTER TABLE dbo.tbltest ALTER COLUMN [ID] UNIQUEIDENTIFIER
    

    Now keep in mind that only the front half of the generated GUID will be non-zero values because a BitInt value is 8 bytes and a UniqueIdentifier is 16 bytes, so you'll end up with Guid's that look like:

    E38E4965-8DFC-4FF3-0000-000000000000

提交回复
热议问题