Incrementing Character value in T-sql(增加 T-sql 中的字符值)
问题描述
我在一列中有 2 组值,即前 4 个字符是字符,接下来的 4 个字符是数字.例如:AAAA1234现在我必须从右端增加值,即当数值达到 9999 时,我必须将字符增加 1 个字符.
I have 2 set of values in a column i.e first 4 character are characters and next 4 character are numeric. Ex:AAAA1234 Now I have to increment the value from right end i.e when numeric value reached 9999 then I have to increment character by 1 character.
示例:考虑存储在列中的最后一个值是 AAAA9999,然后下一个递增的值应该是序列 AAAB9999,..... AABZ9999,... BZZZ9999..... ZZZZ9999(last value).当它达到 ZZZZ9999 时,我必须将值重置为 AAAA0001.
Sample : Consider the last value stored in a column is AAAA9999 then next incremented values should be in a sequence AAAB9999,....... AABZ9999,..... BZZZ9999..... ZZZZ9999(last value). And when it reaches ZZZZ9999 then I have to reset the value to AAAA0001.
如何在 T-SQL 中做到这一点???
How can do it in T-SQL ???
推荐答案
这是一个概念性脚本,它可以满足您的需求.您需要对其进行调整以满足您的要求
Here is a conceptual script, which does what you want. You will need to tweak it to suit your requirements
DECLARE @test table(TestValue char(8))
DECLARE @CharPart char(4),@NumPart int
SET @CharPart = 'AAAA'
SET @NumPart = 1
WHILE @NumPart <=9999
BEGIN
INSERT INTO @test
SELECT @CharPart+RIGHT(('0000'+CAST(@NumPart AS varchar(4))),4)
IF @NumPart = 9999
BEGIN
IF SUBSTRING(@CharPart,4,1)<>'Z'
BEGIN
SET @CharPart = LEFT(@CharPart,3)+CHAR(ASCII(SUBSTRING(@CharPart,4,1))+1)
SET @NumPart = 1
END
ELSE IF SUBSTRING(@CharPart,4,1)='Z' AND SUBSTRING(@CharPart,3,1) <>'Z'
BEGIN
SET @CharPart = LEFT(@CharPart,2)+CHAR(ASCII(SUBSTRING(@CharPart,3,1))+1)+RIGHT(@CharPart,1)
SET @NumPart = 1
END
ELSE IF SUBSTRING(@CharPart,3,1)='Z' AND SUBSTRING(@CharPart,2,1) <>'Z'
BEGIN
SET @CharPart = LEFT(@CharPart,1)+CHAR(ASCII(SUBSTRING(@CharPart,2,1))+1)+RIGHT(@CharPart,2)
SET @NumPart = 1
END
ELSE IF SUBSTRING(@CharPart,1,1)<>'Z'
BEGIN
SET @CharPart = CHAR(ASCII(SUBSTRING(@CharPart,1,1))+1)+RIGHT(@CharPart,3)
SET @NumPart = 1
END
ELSE IF SUBSTRING(@CharPart,1,1)='Z'
BEGIN
SET @CharPart = 'AAAA'
SET @NumPart = 1
INSERT INTO @test
SELECT @CharPart+RIGHT(('0000'+CAST(@NumPart AS varchar(4))),4)
BREAK
END
END
ELSE
BEGIN
SET @NumPart=@NumPart+1
END
END
SELECT * FROM @test
这篇关于增加 T-sql 中的字符值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:增加 T-sql 中的字符值


- 在SQL中,如何为每个组选择前2行 2021-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- SQL 临时表问题 2022-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 更改自动增量起始编号? 2021-01-01