43

i am trying to extract a substring(everything before a hyphen, in this case) from a string as shown below:

Net Operating Loss - 2007
Capital Loss - 1991
Foreign Tax Credit - 1997

and want the year and name(substring before hyphen) separately, using SQL server Management studio 2008. Any advice? or idea how i can achieve this?

3 Answers 3

83
DECLARE @test nvarchar(100)

SET @test = 'Foreign Tax Credit - 1997'

SELECT @test, left(@test, charindex('-', @test) - 2) AS LeftString,
    right(@test, len(@test) - charindex('-', @test) - 1)  AS RightString
3
  • 1
    Should that - 2 be - 1?
    – MaxJ
    Sep 18, 2018 at 10:51
  • 1
    no, there are spaces on both sides of the char '-' @MaxJ
    – pbordeaux
    Sep 19, 2018 at 2:37
  • 1
    @pbordeaux - Ah, yes - missed that, apologies. Was not the case in what I required this for and overlooked that
    – MaxJ
    Sep 19, 2018 at 15:45
7
DECLARE @dd VARCHAR(200) = 'Net Operating Loss - 2007';

SELECT SUBSTRING(@dd, 1, CHARINDEX('-', @dd) -1) F1,
       SUBSTRING(@dd, CHARINDEX('-', @dd) +1, LEN(@dd)) F2
1

This can achieve using two SQL functions- SUBSTRING and CHARINDEX

You can read strings to a variable as shown in the above answers, or can add it to a SELECT statement as below:

SELECT SUBSTRING('Net Operating Loss - 2007' ,0, CHARINDEX('-','Net Operating Loss - 2007'))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.