I need to do the following modifications to a varchar(20) field:
for example
'aèàç=.32s df'
must become
'aeacsdf'
are there special stored functions to achieve this easily?
UPDATE: please provide a T-SQL not CLR solution. This is the workaround I temporarly did because it temporarly suits my needs, anyway using a more elegant approach would be better.
CREATE FUNCTION sf_RemoveExtraChars (@NAME nvarchar(50)) RETURNS nvarchar(50) AS BEGIN declare @TempString nvarchar(100) set @TempString = @NAME set @TempString = LOWER(@TempString) set @TempString = replace(@TempString,' ', '') set @TempString = replace(@TempString,'à', 'a') set @TempString = replace(@TempString,'è', 'e') set @TempString = replace(@TempString,'é', 'e') set @TempString = replace(@TempString,'ì', 'i') set @TempString = replace(@TempString,'ò', 'o') set @TempString = replace(@TempString,'ù', 'u') set @TempString = replace(@TempString,'ç', 'c') set @TempString = replace(@TempString,'''', '') set @TempString = replace(@TempString,'`', '') set @TempString = replace(@TempString,'-', '') return @TempString END GO
You can remove special characters from a database field using REPLACE() function. The special characters are double quotes (“ “), Number sign (#), dollar sign($), percent (%) etc.
SQL Server TRIM() Function The TRIM() function removes the space character OR other specified characters from the start or end of a string. By default, the TRIM() function removes leading and trailing spaces from a string. Note: Also look at the LTRIM() and RTRIM() functions.
The best way to achieve this is very simple and efficient :
SELECT 'àéêöhello!' Collate SQL_Latin1_General_CP1253_CI_AI
which outputs 'aeeohello!'
The string must not be unicode. If you have a nvarchar just cast it to varchar before using the collate.
Here is a function that answers the OP needs :
create function [dbo].[RemoveExtraChars] ( @p_OriginalString varchar(50) ) returns varchar(50) as begin declare @i int = 1; -- must start from 1, as SubString is 1-based declare @OriginalString varchar(100) = @p_OriginalString Collate SQL_Latin1_General_CP1253_CI_AI; declare @ModifiedString varchar(100) = ''; while @i <= Len(@OriginalString) begin if SubString(@OriginalString, @i, 1) like '[a-Z]' begin set @ModifiedString = @ModifiedString + SubString(@OriginalString, @i, 1); end set @i = @i + 1; end return @ModifiedString end
Then, the command:
select dbo.RemoveExtraChars('aèàç=.32s df')
outputs
aeacsdf
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With