用于生成字母数字字符串中的下一个序列的 SQL 代码

SQL code to generate next sequence in a alphanumeric string(用于生成字母数字字符串中的下一个序列的 SQL 代码)
本文介绍了用于生成字母数字字符串中的下一个序列的 SQL 代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我已经在 nvarchar 列中填充了一些字符串值.字符串的格式是这样的:

I have some string values already populated in a nvarchar column. the format of the strings are like this:

例如:16B、23G、128F、128M等...

For example: 16B, 23G, 128F, 128M etc...

我需要从中找出最大值,然后从代码中生成下一个.拾取最大项的逻辑如下:

I need to find out the maximum value from these, then generate the next one from code. The logic for picking up the maximum item is like the following:

  1. 选择数字最大的字符串.
  2. 如果有多个最大的数字,则选择其中最大的字母.

例如,上述系列中最大的字符串是 128M.

For example, the largest string from the above series is 128M.

现在我需要生成下一个序列.下一个字符串将有

Now I need to generate the next sequence. the next string will have

  1. 与最大的数字相同,但字母表增加了 1.I.E.128N
  2. 如果字母达到 Z,则数字增加 1,字母为 A.例如,128Z 的下一个字符串是 129A.

谁能告诉我什么样的 SQL 可以得到我想要的字符串.

Can anyone let me know what kind of SQL can get me the desired string.

推荐答案

假设:

CREATE TABLE MyTable
    ([Value] varchar(4))
;

INSERT INTO MyTable
    ([Value])
VALUES
    ('16B'),
    ('23G'),
    ('128F'),
    ('128M')
;

你可以这样做:

select top 1 
    case when SequenceChar = 'Z' then
        cast((SequenceNum + 1) as varchar) + 'A'
    else
        cast(SequenceNum as varchar) + char(ascii(SequenceChar) + 1)
    end as NextSequence
from (
    select Value, 
        cast(substring(Value, 1, CharIndex - 1) as int) as SequenceNum, 
        substring(Value, CharIndex, len(Value)) as SequenceChar
    from (
        select Value, patindex('%[A-Z]%', Value) as CharIndex
        from MyTable
    ) a
) b
order by SequenceNum desc, SequenceChar desc

SQL 小提琴示例

这篇关于用于生成字母数字字符串中的下一个序列的 SQL 代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

ibtmp1是非压缩的innodb临时表的独立表空间,通过innodb_temp_data_file_path参数指定文件的路径,文件名和大小,默认配置为ibtmp1:12M:autoextend,也就是说在文件系统磁盘足够的情况下,这个文件大小是可以无限增长的。 为了避免ibtmp1文件无止境的暴涨导致
SQL query to group by day(按天分组的 SQL 查询)
What does SQL clause quot;GROUP BY 1quot; mean?(SQL 子句“GROUP BY 1是什么意思?意思是?)
MySQL groupwise MAX() returns unexpected results(MySQL groupwise MAX() 返回意外结果)
MySQL SELECT most frequent by group(MySQL SELECT 按组最频繁)
Include missing months in Group By query(在 Group By 查询中包含缺失的月份)