Remove first and last character if has specific character in sql server?

0

Please login or register to vote for this query.

(click on this box to dismiss)

Motor Vehicle Maintenance and Repair Meta

Q&A about the site for mechanics and DIY enthusiast owners of cars, trucks, and motorcycles

declare @test as table(str varchar(1000));

insert into @test values
('#Test#SQL#'),
('Test#SQL'),
('#Test#SQL'),
('Test#SQL # ');

select case when left(str, 1) = ' # ' and right(str, 1) = '#'
then left((right(str, len(str) - 1)), len((right(str, len(str) - 1))) - 1)
when left(str, 1) = '#' and right(str, 1) <> '#'
then right(str, len(str) - 1)
when left(str, 1) <> '#' and right(str, 1) = '#'
then left(str, len(str) - 1)
else str end as str
from @test;

Enter Parameters

Options:
Switch to main site
loading Hold tight while we fetch your results