Home >Database >Mysql Tutorial >How to Convert Non-Hyphenated VARCHAR to UNIQUEIDENTIFIER in SQL Server?
Efficiently Converting Non-Hyphenated VARCHAR to UNIQUEIDENTIFIER in SQL Server
Direct conversion of non-hyphenated VARCHAR strings representing unique identifiers to the UNIQUEIDENTIFIER data type in SQL Server often fails. Standard CAST
or CONVERT
functions won't work due to the missing hyphens. This necessitates a custom solution.
The following SQL code provides a reliable method for this conversion:
<code class="language-sql">DECLARE @uuid VARCHAR(50) SET @uuid = 'a89b1acd95016ae6b9c8aabb07da2010' SELECT CAST( SUBSTRING(@uuid, 1, 8) + '-' + SUBSTRING(@uuid, 9, 4) + '-' + SUBSTRING(@uuid, 13, 4) + '-' + SUBSTRING(@uuid, 17, 4) + '-' + SUBSTRING(@uuid, 21, 12) AS UNIQUEIDENTIFIER)</code>
This code snippet breaks down the non-hyphenated VARCHAR string into its components (8-4-4-4-12 character segments) and reassembles it with the necessary hyphens, conforming to the UNIQUEIDENTIFIER format. The resulting string is then successfully cast to a UNIQUEIDENTIFIER. This approach ensures accurate and error-free conversion.
The above is the detailed content of How to Convert Non-Hyphenated VARCHAR to UNIQUEIDENTIFIER in SQL Server?. For more information, please follow other related articles on the PHP Chinese website!