Friday, June 22, 2012

MSSQL Character Value Rank

I recently ran into a scenario where a calculation was needed between an INTEGER and a VARCHAR field, with the issue being the VARCHAR field might contain values that could not be converted into an INTEGER type.  To exclude the values that contained text, I thought about adding to the WHERE clause only records with the field in question less than a character value.  But I ended up settling on a solution found on Stack Overflow here, as it works in more scenarios.

I was still curious as to the Character Value rank and after a search for a listing of Characters and their SQL ranking came up empty, I decided to create one with the code below.



In the T-SQL script, I first create a Table Variable to contain the results.  I then populate the table with the potential characters using a WHILE loop and the CHAR() function.  I then use an UPDATE and SELECT statement to calculate the Value Rank of the Character.  Lastly, the results are displayed in Value Rank order.

 Declare @Tbl Table (CharInteger integer, CharResult varchar, ValueRank Integer);  
 Declare @iCount integer;  
   
 SET @iCount = 0;  
   
 While @iCount <= 255  
 BEGIN  
 INSERT INTO @Tbl  
 VALUES  
      (@iCount,  
       Char(@iCount),  
       0);  
 SET @iCount = @iCount + 1;  
 END;  
   
 UPDATE  
      @Tbl  
 SET  
      ValueRank = (SELECT COUNT(*) from @Tbl B WHERE B.CharResult < [@Tbl].CharResult);  
   
 SELECT  
      *  
 FROM  
      @Tbl  
 ORDER BY  
      ValueRank;  

Results:



No comments:

Post a Comment

Please only include comments that add to the substance of the Blog Post:
- Question or request for clarification
- Idea for improvement
- Identifying an issue

Please refrain from promotion.