I have a function which is returning 'Q&A' as QA and 'Q & A ' as ' Q And A' but what i need is like 'Q&A' as Q&A and 'Q & A ' as
'Q And A'. Below is the code.
DECLARE @RawDescription varchar(255) ='Q&A'
SET @RawDescription = REPLACE(@RawDescription, ' & ', ' And ')
WHILE PATINDEX('%[^ ''0-9A-Za-z]%', @RawDescription) > 0
BEGIN
IF SUBSTRING(@RawDescription, PATINDEX('%[^ ''0-9A-Za-z]%', @RawDescription), 1) = '-'
BEGIN
SET @RawDescription = TRIM(REPLACE(@RawDescription, SUBSTRING(@RawDescription, PATINDEX('%[^ ''0-9A-Za-z]%', @RawDescription), 1), ' '))
END
ELSE
BEGIN
SET @RawDescription = TRIM(REPLACE(@RawDescription, SUBSTRING(@RawDescription, PATINDEX('%[^ ''0-9A-Za-z]%', @RawDescription), 1), ''))
END
END
WHILE CHARINDEX(' ', @RawDescription) > 0
BEGIN
SET @RawDescription = REPLACE(@RawDescription, ' ', ' ')
END
select @RawDescription

sasikala sRank #1,091 · 1.7K reputationPosted Dec 11, 2024, 5:17 AM EST
To achieve the desired results where "Q&A" remains as "Q&A" and "Q & A" is transformed into "Q And A," we need to adjust your SQL code slightly to avoid replacing the ampersand in "Q&A."
DECLARE @RawDescription varchar(255) ='Q&A' -- First, handle the replacement of ' & ' with ' And ' SET @RawDescription = REPLACE(@RawDescription, ' & ', ' And ') -- Then, we will replace any unwanted characters while preserving the '&' character WHILE PATINDEX('%[^ ''0-9A-Za-z&]%', @RawDescription) > 0 BEGIN IF SUBSTRING(@RawDescription, PATINDEX('%[^ ''0-9A-Za-z&]%', @RawDescription), 1) = '-' BEGIN SET @RawDescription = TRIM(REPLACE(@RawDescription, SUBSTRING(@RawDescription, PATINDEX('%[^ ''0-9A-Za-z&]%', @RawDescription), 1), ' ')) END ELSE BEGIN SET @RawDescription = TRIM(REPLACE(@RawDescription, SUBSTRING(@RawDescription, PATINDEX('%[^ ''0-9A-Za-z&]%', @RawDescription), 1), '')) END END -- Remove extra spaces WHILE CHARINDEX(' ', @RawDescription) > 0 BEGIN SET @RawDescription = REPLACE(@RawDescription, ' ', ' ') END SELECT @RawDescriptionJayraj ChhayaRank #304 · 8.2K reputationPosted Dec 11, 2024, 5:47 AM EST
Hi
Check below updated code
DECLARE @RawDescription varchar(255) = 'Q & A' SET @RawDescription = REPLACE(@RawDescription, ' & ', ' And ') WHILE PATINDEX('%[^ ''0-9A-Za-z&]%', @RawDescription) > 0 BEGIN IF SUBSTRING(@RawDescription, PATINDEX('%[^ ''0-9A-Za-z&]%', @RawDescription), 1) = '-' BEGIN SET @RawDescription = TRIM(REPLACE(@RawDescription, SUBSTRING(@RawDescription, PATINDEX('%[^ ''0-9A-Za-z&]%', @RawDescription), 1), ' ')) END ELSE BEGIN SET @RawDescription = TRIM(REPLACE(@RawDescription, SUBSTRING(@RawDescription, PATINDEX('%[^ ''0-9A-Za-z&]%', @RawDescription), 1), '')) END END WHILE CHARINDEX(' ', @RawDescription) > 0 BEGIN SET @RawDescription = REPLACE(@RawDescription, ' ', ' ') END SELECT @RawDescription