简体   繁体   中英

SQL Server: How to use substring in a query?

i have this kind of row:

 [Arturo Ochando] <20> 

But i want only:

 Arturo Ochando 

How can i do that ?

And how use this in a 'select' operation ?

update: i would like to find the first and the last '[' ']' and catch only what is inside there.

Example:

voice: English version) [Cobalt Claw]

return

Cobalt Claw

Best regards, Valter Henrique.

Get text between first [ and next ] .

-- 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)

Get text between first [ and last ] .

-- 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)
select substring(field, charindex('[', field) + 1, charindex(']', field) - charindex('[', field) - 1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM