6

I have a Table, Table A, and in table A I have Field A. There are values in field A like the following:

Street A
Street B
,Street C
Street D
etc

I would like to know if there is any SQL that will allow me to either remove the 1st character from Field A where there is a ,.

I have know idea where to start I can select all the rows which have a , in Field A but I don't know where to start when trying to remove it.

w3n2u
  • 333
  • 3
  • 5
  • 13

4 Answers4

13

If you'd rather not care about the length, STUFF is the right candidate :

UPDATE YourTable
SET    YourCol = STUFF(YourCol, 1, 1, '')
WHERE YourCol LIKE ',%'
Serge
  • 6,554
  • 5
  • 30
  • 56
  • To be clear there is no particular need to care about the length with `SUBSTRING` either - it doesn' t matter if it is over specified so you can set it to max int. – Martin Smith Nov 12 '17 at 11:49
4

You could use the RIGHT, LEN and RTRIM functions

UPDATE TableA
SET FieldA = RIGHT(RTRIM(FieldA), LEN(FieldA) - 1)
WHERE FieldA LIKE ',%'

Example

  • @MartinSmith thanks for pointing that out, I've updated it to use the the datalength function –  Jun 20 '13 at 13:05
  • Of course if their column datatype is `UNICODE` or they are on a double byte collation this may not be correct though. – Martin Smith Jun 20 '13 at 13:11
  • i updated for unicode, not sure if double byte collation makes any difference to data length though –  Jun 20 '13 at 13:14
  • [Example of that here](http://stackoverflow.com/questions/176514/what-is-the-difference-between-char-nchar-varchar-and-nvarchar-in-sql-server/8250586#8250586) – Martin Smith Jun 20 '13 at 13:15
  • If you are determined to use `RIGHT` probably the easiest way would be `RIGHT(RTRIM(FieldA), LEN(FieldA) - 1)` – Martin Smith Jun 20 '13 at 13:32
  • That seems so over the top, is there any benefit to using the `RIGHT` function instead of the `SUBSTRING` function –  Jun 20 '13 at 14:18
3
UPDATE YourTable
SET    YourCol = SUBSTRING(YourCol, 2, 0+0x7fffffff) 
WHERE YourCol LIKE ',%'
Martin Smith
  • 438,706
  • 87
  • 741
  • 845
2

You can use TSQL SUBSTRING function

http://msdn.microsoft.com/en-us/library/ms187748.aspx

Use LEN to get the length of the field.

http://msdn.microsoft.com/en-us/library/ms190329.aspx

SUBSTRING(FieldA, 2, LEN(FieldA) - 1)
Jakub Konecki
  • 45,581
  • 7
  • 87
  • 126