如何使用SQL查询自动增加字符串

时间:2019-02-14 06:19:49

标签: mysql

我被困在必须增加字符串的位置,并且我的字符串的类型为C001SC001B001

在我的数据库中,它们的定义类似于

This is the data into my db

我想做的是编写一个查询,该查询检查存在于我的数据库中的先前最高代码,并将其递增为+1

  • 例如C001-> C002, C009 ->C010, C099`-> C100等
  • 类似于SC001-> SC002SC009-> SC010SC099-> SC100等
  • 类似地B001-> B002, B009 ->B010, B099`-> B100等等

我有一个我的朋友建议我使用的查询,但该查询仅包含AAAA-> AAAA01AAAA09-> AAAA10

查询是

    SELECT id AS PrevID, CONCAT(
    SUBSTRING(id, 1, 4),
    IF(CAST(SUBSTRING(id, 5) AS UNSIGNED) <= 9, '0', ''),
    CAST(SUBSTRING(id, 5) AS UNSIGNED) + 1
) AS NextID
FROM (
    -- since you allow strings such as AAAA20 and AAAA100 you can no longer use MAX
    SELECT id
    FROM t
    ORDER BY SUBSTRING(id, 1, 4) DESC, CAST(SUBSTRING(id, 5) AS UNSIGNED) DESC
    LIMIT 1
) x

当我用CategoryCode替换ID时,它给了我PrevID-C004 NextID-C00401,这不是我想要的PrevID-C004NextID->C005

注意,我正在使用sqlServer 5.1

1 个答案:

答案 0 :(得分:1)

只需尝试一下

SELECT 
CategoryCode,CAST(CONCAT(LPAD(CategoryCode,1,0),LPAD(MAX(RIGHT(CategoryCode, 
3)) + 1, 3, 0) ) AS CHAR),
FROM  test

SELECT 
SubCategoryCode,CAST(CONCAT(LPAD(SubCategoryCode,2,0), 
LPAD(MAX(RIGHT(CategoryCode, 3)) + 1, 3, 0) ) AS CHAR), 
FROM  test

SELECT  
BrandCode,CAST(CONCAT(LPAD(BrandCode,1,0), LPAD(MAX(RIGHT(BrandCode, 3)) + 
1, 3, 0))  AS CHAR) FROM  test