0

I need your help real quick.... I use SQL 2008 R2

I have this column that has this kind of data

1_kka
2_bge
3_kil 

the column should have only the number which is

1
2
3

So how should i replace it by using replace and substring?

Thank you!!

1
  • 1
    There is no SQL Server 2012 R2... it's either 2008R2 or 2012? :) Commented Jul 19, 2013 at 18:12

5 Answers 5

2

In MySQL, you can do this remarkably easily by just adding 0 tot he string:

select col + 0
from t

The + 0 treats the string as an integer, and it automatically converts any numbers at the beginning of the string into a number.

In other databases, something like this will work:

select cast(left(col, 1) as int)
from t

Assuming that the initial number has exactly one digit (as in the examples in your question).

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

1 Comment

Sorry I use SQL 2012 R2
1

If you're using SQL Server and if number is not limited to 1 digit you can use

SELECT SUBSTRING(column, 1, CHARINDEX('_', column)-1)
FROM Table

Comments

1

If multiple digits can appear before the underscore, you'll need something like this:

SELECT LEFT(Fieldname,CHARINDEX('_',Fieldname)-1)
FROM table

Comments

1

This will update all values, in every row that contains your underscore.

Update TableName
Set FieldName = Substring(FieldName, 1, CharIndex('_', FieldName) - 1)
Where CharIndex('_', FieldName) >= 1

Comments

0

try this:

update <TABLE> set COL = LEFT(COL,CHARINDEX('_', COL)-1)

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.