Select Distinct REPLACE(REPLACE(REPLACE(REPLACE(Category,' & ','-'),'/',',' ','-') AS Department From Inv WITH(NOLOCK)
我很想知道因为我是一名小型ETL工程师,并希望养成良好的习惯.
显然,在许多情况下,这可能会变得更长.
解决方法
嵌套替换很好,但随着嵌套级别的增加,代码的可读性下降.如果我要替换大量字符,我会选择像下表驱动方法那样更清洁的东西.
declare @Category varchar(25) set @Category = 'ABC & DEF/GHI,LMN OP' -- nested replace select replace(replace(replace(replace(@Category,'-') as Department -- table driven declare @t table (ReplaceThis varchar(10),WithThis varchar(10)) insert into @t values (' & ',('/',(',(' ','-') select @Category = replace(@Category,ReplaceThis,isnull(WithThis,'')) from @t where charindex(ReplaceThis,@Category) > 0; select @Category [Department]