Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove first comma in string using sql

my string like that :

1  ,QCIM1J25836, QCIM1J27637
2  ,QCIM1J25836, QCIM1J27637, QCIM1J27638

I want to remove first comma only it means my output will be for

1  QCIM1J25836, QCIM1J27637
2  QCIM1J25836, QCIM1J27637, QCIM1J27638

may be in other will not be comma...so please tell me how can I update all data like that...

like image 986
Vipin Singhal Avatar asked Jul 06 '26 01:07

Vipin Singhal


2 Answers

In SQL-Server you can do It in multiple ways.

You use STUFF in following:

SELECT col1, 
       STUFF(col2,1,1,'') as [Col Without First Comma]
FROM tbl
WHERE col2 LIKE ',%'

or you can use RIGHT

SELECT col1, 
       RIGHT(col2,LEN(col2)-1) as [Col Without First Comma]
FROM tbl
WHERE col2 LIKE ',%';

or you can use SUBSTRING

SELECT col1,
       SUBSTRING(col2, 2, 255) as [Col Without First Comma]
FROM tbl
WHERE col2 LIKE ',%';

UPDATE

As per your comment you can update in the same ways too:

Using SUBSTRING

UPDATE tbl
SET col2 = SUBSTRING(col2, 2, 255)
WHERE col2 LIKE ',%';

Or using RIGHT

UPDATE tbl 
SET col2 = RIGHT(col2,LEN(col2)-1) 
WHERE col2 LIKE ',%';

Or using STUFF

UPDATE tbl
SET col2 = STUFF(col2,1,1,'')
WHERE col2 LIKE ',%';
like image 69
Stanislovas Kalašnikovas Avatar answered Jul 07 '26 14:07

Stanislovas Kalašnikovas


The following query should work:
It will update all the records in the column.

UPDATE table
SET col2 = CASE WHEN LEFT(col2 ,1) =',' THEN RIGHT(col2,LEN(col2)-1)
                    ELSE col2 END
like image 41
Biswabid Avatar answered Jul 07 '26 14:07

Biswabid