Vaibhav Sinha
Vaibhav Sinha

Reputation: 69

Separate a string in SQL in two parts separated by (hyphen) - and store the two parts in a different variable

I need to separate a string in SQL,

Example,

a='001A01-001A05'

What I need in OUTPUT is,

x='001A01'
y='001A05'

Upvotes: 0

Views: 2059

Answers (3)

Stephen
Stephen

Reputation: 1542

try this using LEFT and RIGHT

DECLARE @str varchar(max)= '001A01-001A05'
select left(@str, charindex('-', @str)-1), 
       right(@str, charindex('-', @str)-1)

Upvotes: 1

John Cappelletti
John Cappelletti

Reputation: 81950

Prdp's answer would be my first choice, but if SQL Server 2012+, another option is PARSENAME()

Declare @a varchar(25)='001A01-001A05'
Select x=ParseName(Replace(@a,'-','.'),2)
      ,y=ParseName(Replace(@a,'-','.'),1)

Returns

x       y
001A01  001A05

Upvotes: 2

Pரதீப்
Pரதீப்

Reputation: 93704

Use LEFT, CHARINDEX and SUBSTRING

DECLARE @char VARCHAR(500)= '001A01-001A05'

SELECT LEFT(@char, Charindex('-', @char) - 1),
       Substring(@char, Charindex('-', @char) + 1, Len(@char)) 

Upvotes: 3

Related Questions