﻿DROP FUNCTION IF EXISTS [dev].[fnGetKopasznev]
GO

CREATE FUNCTION [dev].[fnGetKopasznev](@input_name nvarchar(300)) 
  RETURNS nvarchar(300) 
AS BEGIN
  declare @nev  nvarchar(300),
    @s1         nvarchar(300),
    @i          int,
    @b      char(1),
    @c      char(1)
  SET @nev = LOWER(@input_name collate Latin1_General_CI_AI)
  SET @nev = REPLACE(@nev,'tsch','cscs')
  SET @nev = REPLACE(@nev,'sch','s')
  SET @nev = REPLACE(@nev,'ts','cs')
  SET @nev = REPLACE(@nev,'ch','cs')
  SET @nev = REPLACE(@nev,'th','t')
  SET @nev = REPLACE(@nev,'ly','j')
  SET @nev = REPLACE(@nev,'cz','c')
  SET @nev = REPLACE(@nev,'dr.','')
  SET @nev = REPLACE(@nev,'dr .','')
  SET @nev = REPLACE(@nev,'_','')
  SET @nev = REPLACE(@nev,'á','a')
  SET @nev = REPLACE(@nev,'é','e')
  SET @nev = REPLACE(@nev,'í','i')
  SET @nev = REPLACE(@nev,'ó','o')
  SET @nev = REPLACE(@nev,'ö','o')
  SET @nev = REPLACE(@nev,'ő','o')
  SET @nev = REPLACE(@nev,'ú','u')
  SET @nev = REPLACE(@nev,'ü','u')
  SET @nev = REPLACE(@nev,'ű','u')    
    
  SET @i = 0
  SET @s1 = ''
  SET @b = ''
  SET @c = ' '
  WHILE @i < LEN(@nev) BEGIN
    SET @i = @i + 1
    SET @b = SUBSTRING(@nev, @i, 1)
    IF @b LIKE '[abcdefghijklmnopqrstuvwxyz]' BEGIN
      IF ( @b <> @c ) AND ( ( @b <> 'h') OR ( ( @b = 'h' ) AND (@c IN ('a','e','i','o','u',' ') ) ) ) BEGIN
        IF ( @b <> 'y') OR ( ( @b = 'y' ) AND ( @c IN ('g', 'n', 't') ) )  BEGIN
          SET @s1 += @b
        END  
        ELSE BEGIN
          SET @s1 += 'i'
        END  
      END
    END 
    SET @c = @b
  END
  RETURN @s1
END
GO
