SQL Server:如何在查询中使用子字符串?

时间:2011-04-17 22:09:58

标签: sql sql-server sql-server-2008

我有这样的一行:

[Arturo Ochando]  <20>

但我只想:

Arturo Ochando

我该怎么做?

如何在“选择”操作中使用它?

更新 我想找到第一个和最后一个'['']',只捕捉那里的东西。

示例:

  

声音:英文版)[Cobalt Claw]

返回

  

钴爪

祝你好运, Valter Henrique。

3 个答案:

答案 0 :(得分:2)

在第一个[和下一个]之间获取文字。

-- cte for test data
;with actor_character(character) AS
(
  select 'voice: English version) [Cobalt Claw]' union all
  select 'voice: English version) [Cobalt Claw' union all
  select 'voice: English version)  Cobalt Claw]' union all
  select 'voice: English version) ]Cobalt Claw[' union all
  select 'voice: English version)  Cobalt Claw'
)
select *,
  case
    -- Test for not valid positions
    when Start.Pos = 1 or Stop.Pos = 0
    then character
    else substring(character, Start.Pos, Stop.Pos-Start.Pos)
  end
from actor_character
  cross apply (select charindex('[', character)+1) as Start(Pos)
  cross apply (select charindex(']', character, Start.Pos)) as Stop(Pos)

在第一个[和最后一个]之间获取文字。

-- cte for test data
;with actor_character(character) AS
(
  select 'voice: English version) [Cobalt Claw]' union all
  select 'voice: English version) [Cobalt Claw' union all
  select 'voice: English version)  Cobalt Claw]' union all
  select 'voice: English version) ]Cobalt Claw[' union all
  select 'voice: English version) [Cobalt]Claw]' union all
  select 'voice: English version)  Cobalt Claw'
)
select *,
  case
    -- Test for not valid positions
    when Start.Pos = 0 or Stop.Pos = 0 or Start.Pos > len(character)-Stop.Pos
    then character
    else substring(character, Start.Pos+1, len(character)-Stop.Pos-Start.Pos)
  end

from actor_character
  cross apply (select charindex('[', character)) as Start(Pos)
  cross apply (select charindex(']', reverse(character))) as Stop(Pos)

答案 1 :(得分:1)

答案 2 :(得分:0)

select substring(field, charindex('[', field) + 1, charindex(']', field) - charindex('[', field) - 1)