tags:

views:

603

answers:

4

In SQL, how can I remove the first 4 characters of values of a specific column in a table. Coulmn name is Student Code and an example value id ABCD123Stu1231. I wan to remove first 4 chars from my table for all records

Please guide me

+3  A: 
SELECT RIGHT(MyColumn, LEN(MyColumn) - 4) AS MyTrimmedColumn

Edit: To explain, RIGHT takes 2 arguments - the string (or column) to operate on, and the number of characters to return (starting at the "right" side of the string). LEN returns the length of the column data, and we subtract four so that our RIGHT function leaves the leftmost 4 characters "behind".

Hope this makes sense.

Edit again - I just read Andrew's response, and he may very well have interperpereted correctly, and I might be mistaken. If this is the case (and you want to UPDATE the table rather than just return doctored results), you can do this:

UPDATE MyTable
SET MyColumn = RIGHT(MyColumn, LEN(MyColumn) - 4)

He's on the right track, but his solution will keep the 4 characters at the start of the string, rather than discarding said 4 characters.

Aaron Alton
this will fail for values with < 4 characters. You should add a case block to return the value of the column for < 4.
Scott Ivey
@Scott: True. SUBSTRING deals < 4: it simply returns zero length string...
gbn
Likely the best way to handle it would simply be:UPDATE MyTableSET MyColumn = RIGHT(MyColumn, LEN(MyColumn) - 4)WHERE LEN(MyColumn) > 4The SUBSTRING wouldn't error out, but it would also unnecessarily "update" rows with fewer than four characters. That said, the OP indicated that they wanted to trim the first 4 characters of a specific column - I would assume unless provided with greater detail that ALL rows need to be trimmed.
Aaron Alton
if you're going to run an UPDATE, make sure you don't run it more than once...
spencer7593
@spencer7593 - hahaha...true.You could always add a WHERE clause to be safe:WHERE NOT ISNUMERIC(LEFT(MyColumn,1))
Aaron Alton
+1  A: 

Try this:

update table YourTable
set YourField = substring(YourField, 5, len(YourField)-3);
Andrew Hare
A: 

Here's a simple mock-up of what you're trying to do :)

CREATE TABLE Codes
(
code1 varchar(10),
code2 varchar(10)
)

INSERT INTO Codes (CODE1, CODE2) vALUES ('ABCD1234','')


UPDATE Codes
SET code2 = SUBSTRING(Code1, 5, LEN(CODE1) -4)

So, use the last statement against the field you want to trim :)

The SUBSTRING function trims down Code1, starting at the FIFTH character, and continuing for the length of CODE1 less 4 (the number of characters skipped at the start).

Rob
+2  A: 

Why use LEN so you have 2 string functions? All you need is character 5 on...

...SUBSTRING (Code1, 5, 8000)...
gbn
'cos that hurts my brain ;-)Just kidding - I'm used to (also) working in languages that would throw an error for a statement like that. +1 for the simplicity.
Aaron Alton