Q&A about the site for those interested in the study of the fundamental nature of knowledge, reality, and existence
declare @test as table(str varchar(1000)); insert into @test values ('#Test#SQL#'), ('Test#SQL'), ('#Test#SQL'), ('Test#SQL # '); select case when left(str, 3) = ' # ' and right(str, 3) = ' # ' then left((right(str, len(str) - 3)), len((right(str, len(str) - 3))) - 3) when left(str, 3) = ' # ' and right(str, 3) <> ' # ' then right(str, len(str) - 3) when left(str, 3) <> ' # ' and right(str, 3) = ' # ' then left(str, len(str) - 1) else str end as str from @test;