IsGuid or not isGuid, that is the question…
As I was asked about a functionality how to check a string for being of the type GUID and only finding either solution with massive string operations, or using TRY..CATCH trying to CAST a value and then returning the CAST or CONVERT result, I created a new and simple one, based on a simple pattern matching using the LIKE operator:
CREATE FUNCTION dbo.FnIsGuid
(
@StringToCheck NVARCHAR(36)
)
RETURNS BIT
AS
BEGIN
DECLARE @Result BIT = 0
SELECT @Result = 1
WHERE @StringToCheck LIKE
'[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]-[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]-[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]-[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]-[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]'
RETURN @Result
END
So Krsihna, this one is for you
-Jens
Comments
Anonymous
September 07, 2011
WHERE @StringToCheck LIKE REPLACE('00000000-0000-0000-0000-000000000000', '0', '[0-9a-fA-F]')Anonymous
September 07, 2011
Same Code, better to read. Good suggestion :-) Although with both solutions, once created you won´t touch them ever again.