06 January 2016

IsHex function for SQL Server

 IF EXISTS (  
   SELECT * FROM sysobjects WHERE id = object_id(N'fnIsHex')   
   AND xtype IN (N'FN', N'IF', N'TF')  
 )  
   DROP FUNCTION dbo.fnIsHex  
 GO  
 CREATE FUNCTION dbo.fnIsHex(@s VARCHAR(50) )   
 --Returns true if the string is a valid hexadecimalal number.   
 RETURNS bit  
 AS  
 BEGIN  
 /*  
 Description: Determine if a string represent an Hexadecimal value  
 Author:   Leo Fong  
 Created Date:06 Jan 2015  
 Usage: select dbo.fnIsHex('EX0429168AE12A80')  
     select dbo.fnIsHex('E0429168AE12A80')  
 */  
 DECLARE @i int, @temp char(1), @bool bit  
 SET @i=1  
 SET @bool=0  
 WHILE (@i<=LEN(@s))  
 BEGIN  
   SELECT @temp=SUBSTRING(@s,@i,1)  
   if ((@temp<='f') AND (@temp>='a')) OR ((@temp<='F') AND (@temp>='A')) OR ((@temp<='9') AND (@temp>='0'))   
     BEGIN  
       SET @bool=1  
     END  
   ELSE  
     BEGIN  
       SET @bool=0  
       RETURN @bool  
     END  
   SELECT @i=@i+1  
 END  
 RETURN @bool  
 END  

No comments:

Post a Comment