Is there a smarter way to remove all special characters rather than having a series of about 15 nested replace statements?
The following works, but only handles thr
Create a function:
CREATE FUNCTION dbo.StripNonAlphaNumerics
(
@s VARCHAR(255)
)
RETURNS VARCHAR(255)
AS
BEGIN
DECLARE @p INT = 1, @n VARCHAR(255) = '';
WHILE @p <= LEN(@s)
BEGIN
IF SUBSTRING(@s, @p, 1) LIKE '[A-Za-z0-9]'
BEGIN
SET @n += SUBSTRING(@s, @p, 1);
END
SET @p += 1;
END
RETURN(@n);
END
GO
Then:
SELECT Result = dbo.StripNonAlphaNumerics
('My Customer''s dog & #1 friend are dope, yo!');
Results:
Result
------
MyCustomersdog1friendaredopeyo
To make it more flexible, you could pass in the pattern you want to allow:
CREATE FUNCTION dbo.StripNonAlphaNumerics
(
@s VARCHAR(255),
@pattern VARCHAR(255)
)
RETURNS VARCHAR(255)
AS
BEGIN
DECLARE @p INT = 1, @n VARCHAR(255) = '';
WHILE @p <= LEN(@s)
BEGIN
IF SUBSTRING(@s, @p, 1) LIKE @pattern
BEGIN
SET @n += SUBSTRING(@s, @p, 1);
END
SET @p += 1;
END
RETURN(@n);
END
GO
Then:
SELECT r = dbo.StripNonAlphaNumerics
('Bob''s dog & #1 friend are dope, yo!', '[A-Za-z0-9]');
Results:
r
------
Bobsdog1friendaredopeyo