0

I am working in SQL server. I have some number like 130-0029. I need to get the integer after the - delimiter out of it. So in this example I need to return 29. These are the following scenarios I have with this,

  • The pattern may differ like 130-00000029 or 130-0029.
  • If there are all 0's then print 0, else get actual number like 29.

Please advise/suggest me on this.

2
  • Break it up into multiple number-type fields and print them that way? Commented Nov 5, 2015 at 17:42
  • 1
    130-0029 is not a valid number. I assume you mean the portion after the -?? Then as @AdamV suggests cast that portion to an int. Commented Nov 5, 2015 at 17:43

4 Answers 4

2

Here is an example:

declare @s varchar(100) = '130-0029'
select cast(substring(@s, patindex('%[-]%', @s) + 1, len(@s)) as int)

You may need to cast to some numeric if the number overflows ineteger type.

Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

DECLARE @num varchar(50) = '130-0029'
SELECT CAST(SUBSTRING(@num, CHARINDEX('-', @num) + 1, LEN(@num)) AS INT)

Here is a fiddle.

Comments

0

This also works if the - is missing. But if what follows is not a number it will give an error.

declare @string as varchar(100)
set @string = '130-0029'

select convert(int,Right(@string, LEN(@string)-CHARINDEX('-', @string)))

Comments

0

Probably not so different than other answers, but this works using STUFF too:

DECLARE @String VARCHAR(10) = '130-0029';

SELECT CONVERT(INT, STUFF(@String, 1, CHARINDEX('-', @String), ''));

See this running in Query Stack Exchange.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.