-- First replaces special characters with similar safe ones.
It appears as though you want to replace open quote with regular quote, close quote with regular quote etc... There's a trick you can use to do this without having to mess around with a bunch of replaces. I don't pretend to know everything there is to know about collations, but I do know that they can do some pretty strange things you don't expect and sometimes you can use that to your advantage.
For example:
Declare @Temp VarChar(100)
SET @Temp = '”“‘’–'
Select @Temp,
@Temp Collate SQL_Latin1_General_Cp850_CI_AS
When you run the code above, you will see that the data type is varchar. We set a string with open quote, close quote, etc... If you do not specify a collation, sql will return the data using the default database collation. If you do specify a collation, SQL will return the data using the collation.
As you can see, all of the special characters that you want to replace with "safe" special characters are in fact replaced.
Pulling this all together:
Alter Function [dbo].[RemoveSpecialCharacters](@Temp VarChar(1000))
Returns VarChar(1000)
AS
BEGIN
DECLARE @KeepValues as varchar(50)
SET @Temp = @Temp Collate SQL_Latin1_General_Cp850_CI_AS
SET @KeepValues = '%[^a-z0-9()."`'':;,#&+*\/-[[][]]]%'
WHILE PatIndex(@KeepValues, @Temp) > 0
SET @Temp = Stuff(@Temp, PatIndex(@KeepValues, @Temp), 1, '')
RETURN @Temp Collate Database_Default
END
Note that inside the function, the data is converted to a different collation, and the return value converts it back to the database's default collation.
I also put the open square bracket and close square bracked in to the KeepValues.
Using the replace function is not necessarily bad, but converting collations will execute faster and will product the same results. Scalar functions are notorious as performance killers, so it is in your best interest to make them as fast as possible (and you should be pleased with the performance of this function).
Now... I said earlier that I do not know everything there is to know about collations, so there may be some unexpected. Most of the characters will be the same, but there are some difference:
€ ?
?
‚ '
ƒ ƒ
„ "
… .
† ┼
‡ ╬
ˆ ^
‰ %
Š S
‹ <
Œ O
?
Ž Z
?
?
‘ '
’ '
“ "
” "
•
– -
— -
˜ ~
™ T
š s
› >
œ o
?
ž z
Ÿ Y
With the data shown above, you can interpret this as: the first character will be replaced with the second character when you convert the collation as I show in the code above.