Increment a varchar in SQL

后端 未结 2 992
情歌与酒
情歌与酒 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: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.

提交回复
热议问题