sql server 去掉 某个字符串 前面的某个字符

时间:2021-02-21 15:07:44

因为这面的数据库比较多,数据也比较多,但是有个遗留的历史数据问题;就是某个字符串前面有个英文逗号;

现在需求就是要去掉这个英文逗号,用脚本跑数据库也行,但是这里用sql 语句来去掉;

以下是完整的代码,这里做个记录

DECLARE @cursor CURSOR;
DECLARE @id    int;
DECLARE @Staging    varchar(max);
DECLARE @Staging_tmp    varchar(max);
DECLARE @str_len int;
DECLARE @start_num    int;

set @cursor = CURSOR FOR SELECT id,Staging FROM proj_dong_info where Staging <> '' and Staging is not null;
OPEN @cursor
    FETCH NEXT FROM @cursor INTO @id,@Staging
    WHILE(@@FETCH_STATUS=0)
        BEGIN
        SET @Staging_tmp = ltrim(@Staging);
        SET @start_num = patindex('%,%',@Staging_tmp);
        IF @start_num = 1
            BEGIN
                SET @start_num = patindex('%,%',@Staging);
                SET @str_len = datalength(@Staging);
                SET @Staging = substring(@Staging,@start_num+1,@str_len);
                --PRINT @Staging;
                --PRINT @id;
                update proj_dong_info set Staging = @Staging where id = @id;
            END
            FETCH NEXT FROM @cursor INTO @id,@Staging
        END
    CLOSE @cursor
    DEALLOCATE @cursor