Save GUIDs with hyphens in MSSQL
When you're saving a GUID to the database as a string
value, you should save them with hyphens. That way, you can later cast is as a uniqueidentifier
, which is SQL Server's native GUID type.
If you can, you should save it as a uniqueidentifier
of course. However, in certain scenarios you cannot dictate the schema you save to, only its content.
Casting is really awkward when you have to work with 7fb4438f3df94354aff0d91048385a4f instead of 7fb4438f-3df9-4354-aff0-d91048385a4f. You need to re-insert the hyphens with substring, and then cast it.
But when you already have it, you can just CAST('7fb4438f-3df9-4354-aff0-d91048385a4f' as uniqueidentifier)
and out comes a nice type.