Increment a varchar in SQL

后端 未结 2 987
情歌与酒
情歌与酒 2021-01-26 13:07

Basically, I want to increment a varchar in SQL the has a value of \"ABC001\".

I have code that adds one to an int, but I don\'t know how to get it working for a varchar

相关标签:
2条回答
  • 2021-01-26 13:08
    update 
        [table] 
    set [nxt_no] = case when PATINDEX('%[0-9]%', [nxt_no]) > 0 then 
              left([nxt_no], PATINDEX('%[0-9]%', [nxt_no])-1) -- Text part
              + -- concat
              right( REPLICATE('0', LEN([nxt_no]) - PATINDEX('%[0-9]%', [nxt_no])+1) + convert( varchar, convert(int, right([nxt_no], LEN([nxt_no]) - PATINDEX('%[0-9]%', [nxt_no])+1))+1), LEN([nxt_no]) - PATINDEX('%[0-9]%', [nxt_no])+1)
    else 
        [nxt_no] end
    
    0 讨论(0)
  • 2021-01-26 13:27

    Well, you can do something like this:

    update table
        set nxt_no = left(next_no, 3) +
                      right('0000000' + cast(substring(next_no, 4, 100)+1 as varchar(255)), 4)
    

    A bit brute force in my opinion.

    By the way, you could use an identity column to autoincrement ids. If you then want to put a fixed prefix in front, you ca use a calculated column. Or take Bohemian's advice and store the prefix and number in different columns.

    0 讨论(0)
提交回复
热议问题