0

I have multiple columns where one of them has varchar values as follow.

1
2
4
02
05
6
03
06
123
32
87

I want to find any record that has values starting with 0 > remove that 0 (so 02 > 2) and update that field so there is no value starting with 0.

How can I go about doing that instead of manually updating each record that has 0 in the front? Is that even possible?

Thank you

2
  • 1
    Why is this column varchar at all? Why not simply converting the whole column to integer? Commented Feb 28, 2013 at 16:10
  • I am not really sure behind the reason for choosing varchar data type. converting the whole column to int sounds like a good idea. Commented Feb 28, 2013 at 16:26

3 Answers 3

5

The following code removes the leading zeros by casting the value to an integer and back to a character string:

update t
    set col = cast(cast(col as int) as varchar(255))
    where t.col like '0%'
Sign up to request clarification or add additional context in comments.

1 Comment

This column is right now varchar > I want to remove all the leading 0's and convert it to int. would disregarding outer case in your query do it?
2

You can use the following:

update yourtable
set col = substring(col, 2, len(col)-1)
where left(col, 1) = '0'

See SQL Fiddle with Demo

Comments

1

Run this query until everything is filtered out I guess...

UPDATE Table SET Column=RIGHT(Column, LEN(Column)-1) WHERE Column LIKE '0%';

[Edit] Gordon's approach is probably better.

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.