sql中字符串之间的序号

时间:2016-06-23 08:41:43

标签: sql sql-server tsql

我有一个像这样的存储过程

declare @Tmp varchar(60)
declare @Hasil varchar(60)
declare @PFID varchar(50)
declare @CntPFID int
declare @PrevPFID varchar(60)
DECLARE @CheckLetter CHAR(5)

set @PFID = 'PF-FB/ALL/009/MKX/VI/16'

set @CheckLetter = (UPPER(RIGHT((CAST(SUBSTRING(@PFID, 10, 4) AS VARCHAR(5))), 3)))

select @CntPFID = count(pfid) 
from pf 
where pfid like '%'+ right(@PFID, 9) 
  and pfid like ''+  left(@PFID, 13) +'%'

if @CntPFID = 1
begin
    set @Tmp = (UPPER(RIGHT((CAST(SUBSTRING(@PFID, 10, 4) AS VARCHAR(5))), 3))) + '-' + '01'
    set @Hasil = replace(@PFID, replace(@CheckLetter, ' ', ''), @Tmp)
end
else 
begin
    set @Tmp = (UPPER(RIGHT((CAST(SUBSTRING(@PFID, 10, 4) AS VARCHAR(5))), 3))) + '-0' + cast(@CntPFID as varchar(3))
    set @Hasil = replace(@PFID, replace(@CheckLetter, ' ', ''), @Tmp)
end

select @Hasil 

当记录数据已达到'PF-FB / ALL / 009-09 / MKX / VI / 16'时,我被卡住了下一个数字变为PF-FB / ALL / 009- 010 / MKX / VI / 16(有三位数= 010),我希望它是PF-FB / ALL / 009- 10 / MKX / VI / 16(运行2位数)。

如果>是否有动态方式而不使用其他条件9 ......?

1 个答案:

答案 0 :(得分:0)

您需要更改的表达式:'-0' + cast(@CntPFID as varchar(3)),请尝试以下方式:

declare  @CntPFID int;
set @CntPFID = 9;
select '-' + right('00'+ cast(@CntPFID as varchar(3)),2)
set @CntPFID = 11;
select '-' + right('00'+ cast(@CntPFID as varchar(3)),2)