Showing posts with label How to Remove Duplicate Character from String in SQL. Show all posts
Showing posts with label How to Remove Duplicate Character from String in SQL. Show all posts

Friday, May 20, 2016

How to Remove Duplicate Character from String in SQL

Code Snippet 
  1. CREATE FUNCTION[dbo].[FUN_Remove_Duplicate_Char](@Input[varchar](max))  
  2. RETURNS[varchar](max)  
  3. AS  
  4. BEGIN  
  5. DECLARE @Count int;  
  6. DECLARE @Return_String[varchar](max);  
  7. DECLARE @Char_Index int;  
  8. DECLARE @Temp_Str[varchar](max);  
  9. SET @Count = 0;  
  10. SET @Return_String = @Input;  
  11. WHILE @Count <= 255  
  12. BEGIN  
  13. SET @Char_Index = CHARINDEX(CHAR(@Count), @Return_String, 0);  
  14. IF(@Char_Index > 0)  
  15. BEGIN  
  16. SET @Temp_Str = SUBSTRING(@Return_String, @Char_Index + 1, LEN(@Return_String));  
  17. SET @Temp_Str = REPLACE(@Temp_Str, CHAR(@Count), '');  
  18. SET @Return_String = SUBSTRING(@Return_String, 1, @Char_Index) + @Temp_Str;  
  19. END  
  20. SET @Count = @Count + 1;  
  21. END  
  22. RETURN @Return_String;  
  23. END  
Example 
  1. SELECT dbo.FUN_Remove_Duplicate_Char('Hello How Are You') AS String_;   
Output:
 
Helo wArYu