开发者

SQL Server GUID to VarChar(36) or Char(36)?

I am replacing some GUID column types, since I need to do some Group By work in MSSQL 2008. I was about to change the types to Char(36) since I know the exact size of the value, but after Googling a bit I see lots of people doing Varchar(36) instead. 开发者_如何转开发Isn't it better to do CHAR in this case?


The difference between CHAR and VARCHAR is how space is allocated. CHAR fields are always the size defined, but until a VARCHAR field actually has data in it, then it will occupy 0 bytes.

In your case though, because you're always going to be storing 36 characters, I would suggest you keep using CHAR. If you were storing data of varying length, go with VARCHAR.

However, are you really trying to use a GROUP BY on a GUID? They are called "Globally Unique Identifier" for a reason. Or are you splitting them up, and grouping by certain sections of the GUID (which can be the same, but overall, generally, none are the same).


The quick answer: Use CHAR(36) or better yet BINARY(16).

The long answer: You would probably be better off leaving the column types alone and using CAST in your queries.

DECLARE @a TABLE (x UNIQUEIDENTIFIER, y INT)
-- Insert some data here
SELECT
    MIN(y),
    CAST(a.x AS BINARY(16))
FROM
    @a AS a
GROUP BY
    CAST(a.x AS BINARY(16))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜