SQL Server IsGuid() function
A simple function that checks if a passed string is a GUID.
create function IsGuid ( @testString varchar(38)) returns int as begin declare @ret int select @ret = 0, @testString = replace(replace(@testString, '{', ''), '}', '') if len(isnull(@testString, '')) = 36 and @testString NOT LIKE '%[^0-9A-Fa-f-]%' and -- check for proper positions of hyphens (-) charindex('-', @testString) = 9 and charindex('-', @testString, 10) = 14 and charindex('-', @testString, 15) = 19 and charindex('-', @testString, 20) = 24 and charindex('-', @testString, 25) = 0 set @ret = 1 return @ret end go select dbo.IsGuid ('DAB1df7F-BCB8-4935-9364-f140F64EE5F7') select dbo.IsGuid ('{DAB1df7F-BCB8-4935-9364-f140F64EE5F7}') go drop function dbo.IsGuid
Legacy Comments
Seventhnight
2006-03-31 |
re: SQL Server IsGuid() function Here's another style using replicate :) [code] create function IsGuid ( @testString varchar(38)) returns int as begin declare @ret int select @ret = 0, @testString = replace(replace(@testString, '{', ''), '}', '') Select @ret = case when @testString like (replicate('[0-9A-Fa-f]',8) + '-' + replicate('[0-9A-Fa-f]',4) + '-' + replicate('[0-9A-Fa-f]',4) + '-' + replicate('[0-9A-Fa-f]',4) + '-' + replicate('[0-9A-Fa-f]',12)) then 1 else 0 end return @ret end go select dbo.IsGuid ('DAB1df7F-BCB8-4935-9364-f140F64EE5F7') select dbo.IsGuid ('{DAB1df7F-BCB8-4935-9364-f140F64EE5F7}') select dbo.IsGuid ('3DAB1df7F-BCB8-4935-9364-f140F64EE5F7') go drop function dbo.IsGuid [/code] |
mladen
2006-03-31 |
re: SQL Server IsGuid() function good one! |
sanjoy
2007-08-02 |
re: SQL Server IsGuid() function very good! |
malik
2007-09-05 |
re: SQL Server IsGuid() function Very useful! Thank you very much |
Fox
2008-03-12 |
re: SQL Server IsGuid() function Cool! Thank you very much |
Fox
2008-03-12 |
re: SQL Server IsGuid() function Cool! Thank you very much |