Any one know a good way to remove punctuation from a field in SQL Server?
I\'m thinking
UPDATE tblMyTable SET FieldName = REPLACE(REPLACE(REPLACE(FieldNa
I took Ken MC's solution and made it into an function which can replace all punctuation with a given string:
----------------------------------------------------------------------------------------------------------------
-- This function replaces all punctuation in the given string with the "replaceWith" string
----------------------------------------------------------------------------------------------------------------
IF object_id('[dbo].[fnReplacePunctuation]') IS NOT NULL
BEGIN
DROP FUNCTION [dbo].[fnReplacePunctuation];
END;
GO
CREATE FUNCTION [dbo].[fnReplacePunctuation] (@string NVARCHAR(MAX), @replaceWith NVARCHAR(max))
RETURNS NVARCHAR(MAX)
BEGIN
DECLARE @Result Varchar(max) = @string;
DECLARE @BadChars Varchar(12) = '%[^a-z0-9]%'; -- to leave spaces - SELECT @BadChars = '%[^a-z0-9] %'
DECLARE @p int = PatIndex(@BadChars,@Result);
DECLARE @searchFrom INT;
DECLARE @indexOfPunct INT = @p;
WHILE @indexOfPunct > 0 BEGIN
SET @searchFrom = LEN(@Result) - @p;
SET @Result = Left(@Result, @p-1) + @replaceWith + Substring(@Result, @p+1,LEN(@Result));
SET @IndexOfPunct = PatIndex(@BadChars, substring(@Result, (LEN(@Result) - @SearchFrom)+1, LEN(@Result)));
SET @p = (LEN(@Result) - @searchFrom) + @indexOfPunct;
END
RETURN @Result;
END;
GO
-- example:
SELECT dbo.fnReplacePunctuation('This is, only, a tést-really..', '');
Output:
Thisisonlyatéstreally