I have been using the REPLACE function to remove characters from a text value in a table. It has just grown over time and now the query is quite messy.
What can I do to make this more efficient? Is there a Regex example that I could implement?
Query:
SELECT
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(dbo.[RemoveNumericCharacters](Filename), '.xlsx', '')
, '.xls', '')
,'csv', '')
,'---_pdf', '')
,'.', '')
,'-Jun-', '')
,'-Jul-', '')
,'Jul', '')
,'__', '_')
as 'ConvertedFilename'
FROM @Files
Function:
ALTER Function [dbo].[RemoveNumericCharacters](@Temp nvarchar(1000))
Returns nvarchar(1000)
AS
Begin
Declare @NumRange as varchar(50) = '%[0-9]%'
While PatIndex(@NumRange, @Temp) > 0
Set @Temp = Stuff(@Temp, PatIndex(@NumRange, @Temp), 1, '')
Return @Temp
End
Best Answer
I think you'd better create a filter table in which you put your replacement string pairs and then you can create a function to remove source string with your filter table.
Here is the example
In future, if you have more replacement needed, just add them to the table
dbo.Filter
and you do not need to change anything elsewhere.