将varchar值'A0001'转换为数据类型int时转换失败

时间:2015-07-09 13:17:11

标签: sql sql-server tsql casting

使用此脚本时:

DECLARE @FORDERBZV2     varchar(20)
DECLARE @FORDERBZV          varchar(20)

SELECT  @FORDERBZV      = (SELECT TOP 1 [FOR] FROM [Mil].[dbo].[FXO] where FOR like 'T0%' order by FOR desc)

--[FOR] is declared as varchar(20)  
SELECT  @FORDERBZV2 = right (@FORDERBZV, 19) + 1

--and after i run
insert into [Mil].[dbo].[FEO]
Values (@FORDERBZV2,....)

我收到此错误:

  

Msg 245,Level 16,State 1,Line 6
  将varchar值'T000005571'转换为数据类型int。

时转换失败

我不明白为什么,因为所有文件都声明为VARCHAR(20):

FOR from [Mil].[dbo].[FXO] = VARCHAR(20)
@FORDERBZV  =  VARCHAR(20)
@FORDERBZV  =  VARCHAR(20)

此外,该脚本将正常运行一次,但当我尝试再次运行它时,我收到错误。

1 个答案:

答案 0 :(得分:0)

所以,问题出在这个代码行:SELECT @FORDERBZV2 = right (@FORDERBZV, 19) + 1 你得到错误的原因是你的字符串实际上不是20个字符长,但它更短,所以right函数只返回整个字符串。

我假设您希望通过零填充连续数字得到字母T,所以您应该做这样的事情:

DECLARE @FORDERBZV2     varchar(20)
DECLARE @FORDERBZV          varchar(20)

SELECT  @FORDERBZV      = (SELECT TOP 1 [FOR] 
                           FROM [Mil].[dbo].[FXO] 
                           WHERE [FOR] 
                           LIKE 'T0%' 
                           ORDER BY [FOR] DESC)

SELECT  @FORDERBZV2 = 'T' + RIGHT(
                            REPLICATE('0', LEN(@FORDERBZV)-1) + 
                            CAST (
                            CAST(RIGHT(@FORDERBZV, LEN(@FORDERBZV)-1) AS int) + 1 
                            AS varchar(20))
                            , LEN(@FORDERBZV)-1)

insert into [Mil].[dbo].[FEO]
Values (@FORDERBZV2,....)

see fiddle here.