Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
SQL
declare @string varchar(20)
set @string='e33-B6661-C1'
select substring(@string,charindex('-',@string)+1,charindex('-',@string,charindex('-',@string)+1)-charindex('-',@string)-1)



This query get: B6661

but we need result: C1
: e33-B6661
Posted
Updated 23-Jul-14 19:27pm
v3
Comments
Sergey Alexandrovich Kryukov 24-Jul-14 1:07am    
Why not having three different attributes (as as many as needed) for components of this string?
—SA

Hi,

Use this to achieve your output

SQL
declare @string varchar(20)
set @string='e33-B6661-C1'

select @string


to get the output "B6661-C1"

SQL
select substring(@string,charindex('-',@string)+1,len(@string)-charindex('-',@string)+1)


to get the output "C1"

SQL
select substring(substring(@string,charindex('-',@string)+1,len(@string)-charindex('-',@string)+1)
,charindex('-',substring(@string,charindex('-',@string)+1,len(@string)-charindex('-',@string)+1))+1,
3)
 
Share this answer
 
v2
Try:
SQL
declare @string varchar(20)
set @string='e33-B6661-C1'
SET @STRING = SUBSTRING(@string, CHARINDEX('-', @string) + 1, 9999)
SELECT SUBSTRING(@string, CHARINDEX('-', @string) + 1, 9999)
You can do it all in the SELECT statement, but you need to replace both references to @string with the SET SUBSTRING value.
 
Share this answer
 
Hi, another way
SQL
declare @string varchar(20)
set @string='e33-B6661-C1'
select right(@string,2), left(@string,9)--if format is always same 000-00000-00
SELECT right(@string, charindex('-', reverse(@string))-1) , left(@string,len(@string)- charindex('-', reverse(@string))) --if format is not fixed and dash is separator

Happy Coding!
:)
 
Share this answer
 
This will help you :)

SQL
declare @string varchar(20)
set @string='e33-B6661-C1'
select substring(@string,1,charindex('-',@string,charindex('-',@string)+1)-1)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900