增加varchar值 [英] Increment a varchar value

查看:71
本文介绍了增加varchar值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,
我需要将varchar值加1.

例如.

Hi all,
I need to increment a varchar value by 1.

For eg.

declare @maxid varchar(10)
     set     @maxid = ''AR00001''
     select  @maxid = @maxid + convert(varchar(10),''1'')




我得到的输出是

AR000011

但是我需要AR00002作为输出.

请建议我.


谢谢
Ismail




The output i got is,

AR000011

But i need AR00002 as output.

Kindly suggest me.


Thanks
Ismail

推荐答案

使用以下代码

use the below code

select CONVERT(varchar,substring('AR00001',1,2)) +
       RIGHT(REPLICATE('0',5) + convert(varchar,(CONVERT(int, substring('AR00001',3,5)) + 1)) ,5);


``AR00001''是一个字符串.现在,当您向其中添加"@maxid"时,基本上就是将某些内容连接到字符串中.因此,您得到的结果是预期的.

如果需要将AR00001递增到AR00002,AR00003等,则需要将字符串部分("AR")和数字部分分开,对数字进行递增并再次连接.

尝试做.如果仍然无法获得预期的结果,请返回.
''AR00001'' is a string. Now when you adding ''@maxid'' to it, you are basically concatenating something to a string. So the result you are getting is expected.

If you need to increment AR00001 to AR00002, AR00003 and so on, you need to separate string part (''AR'') and number part, increment the number and concatenate again.

Try doing it. Get back if you still don''t get the desired results.


下面的代码将满足您的要求.

Below code will meet your requirement.

DECLARE @Seed VARCHAR(10) = 'AR00004'
DECLARE @IncrementedValue INT = CONVERT(varchar,CONVERT(int, substring(@Seed,3,LEN(@Seed)-1)))+ 1
SELECT CONVERT(varchar, substring(@Seed,1,2)) + SUBSTRING('00000',1, 5 - LEN(convert(varchar,@IncrementedValue))) + Convert(varchar,@IncrementedValue)


这篇关于增加varchar值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆