2016-08-23 38 views
1

我有一個name列這在某些細胞中含有括號字符串。刪除字符串(),包括()在SQL Server 2008

實例:

Smith (Divorced) 
Jones 
Janes 
Renold (Deaceased)... 

等。我需要徹底刪除括號內的部分。

Smith 
Jones 
Janes 
Renold 

想盡各種CHARINDEX的和REPLACE但要麼得到一個無效的lenght錯誤,或者它只是刪除了一部分。

回答

2

這裏就是你基本上需要,只需修改,以滿足您的查詢:

declare @tmp table (name varchar(100)) 
insert @tmp values ('smith (divorced)') , ('jones'), ('renold (deceased)...') 

select name 
    , case 
     when charindex('(', name, 1) > 0 
      then rtrim(left(name, charindex('(', name, 1) - 1)) 
     else name 
     end as [name] 
from @tmp 

如果你需要更換你的數據,只是發出UPDATE,象下面這樣:

UPDATE Persons_Table 
SET Name = case 
      when charindex('(', Name, 1) > 0 
       then rtrim(left(Name, charindex('(', Name, 1) - 1)) 
      else Name 
      end 
WHERE charindex('(', Name, 1) > 0 -- could prove useful since you might not want to go 
            -- over all of the data