Saturday, August 25, 2012

Check given string is Guid or not in SQL Server



Below function is used to find whether given string is Valid Guid or not.


Create function [dbo].[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



Usage

select  dbo.isGuid('some string')


No comments: