用于生成字母数字字符串中的下一个序列的 SQL 代码
- 作者: 贝仔
- 来源: 51数据库
- 2022-12-06
问题描述
我已经在 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:
- 选择数字最大的字符串.
- 如果有多个最大的数字,则选择其中最大的字母.
例如,上述系列中最大的字符串是 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.I.E.128N
- 如果字母达到 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 小提琴示例
推荐阅读
热点文章
检查拆分键盘
0
带有“上一个"的工具栏和“下一个"用于键盘输入AccessoryView
0
Activity 启动时显示软键盘
0
UIWebView 键盘 - 摆脱“上一个/下一个/完成"酒吧
0
在 iOS7 中边缘滑动时,使键盘与 UIView 同步动画
0
我的 iOS 应用程序中的键盘在 iPhone 6 上太高了.如何在 XCode 中调整键盘的分辨率?
0
android:inputType="textEmailAddress";- '@' 键和 '.com' 键?
0
禁用 iPhone 中键盘的方向
0
Android 2.3 模拟器上的印地语键盘问题
0
keyDown 没有被调用
0
