我已经在stackoverflow上看到了这个问题,但似乎有很多针对这种情况量身定制的解决方案。据我所知,似乎我有一个独特的情况。我正在运行这个sql语句
use IST_CA_2_Batch_Conversion
GO
--T-SQL script to populate the Match type column
declare @MatchType varchar(16),
@PK varchar(500),
@CAReturnCode VARCHAR(255),
@CAErrorCodes VARCHAR(255)
declare cursor1 cursor fast_forward for
select
["Ref#"],
["Return Code"],
["Error Codes"]
from CACodes2MatchType
open cursor1
fetch next from cursor1 into @PK,@CAReturnCode,@CAErrorCodes
while @@fetch_status = 0
begin
set @MatchType = dbo.GetMatchType(@CAReturnCode,@CAErrorCodes)
update CACodes2MatchType
set [Match Type] = @MatchType
where ["Ref#"] = @PK
fetch next from cursor1 into @PK,@CAReturnCode,@CAErrorCodes
end
close cursor1
deallocate cursor1
会失败
set @MatchType = dbo.GetMatchType(@CAReturnCode,@CAErrorCodes)
以下是GetMatchType函数的开始代码:
-- Batch submitted through debugger:
SQLQuery14.sql|6|0|C:\Users\b01642a\AppData\Local\Temp\~vs1C8E.sql
CREATE FUNCTION [dbo].[GetMatchType](@CAReturnCode VARCHAR(255), @CAErrorCodes
VARCHAR(255))
RETURNS VARCHAR(16)
BEGIN
DECLARE @MatchType VARCHAR(16);
DECLARE @errorCodes TABLE(Pos INT, Code CHAR(2));
DECLARE @country INT; -- 1 is US, 2 is Canada
DECLARE @numMinorChanges INT;
DECLARE @numMajorChanges INT;
DECLARE @numSingleCodes INT;
DECLARE @returnCode INT;
DECLARE @verified VARCHAR(16);
DECLARE @goodFull VARCHAR(16);
DECLARE @tentativeFull VARCHAR(16);
DECLARE @poorFull VARCHAR(16);
DECLARE @multipleMatch VARCHAR(16);
DECLARE @unmatched VARCHAR(16);
SET @verified = 'Verified';
SET @goodFull = 'Good Full';
SET @tentativeFull = 'Tentative Full';
SET @poorFull = 'Poor Full';
SET @multipleMatch = 'Multiple Match';
SET @unmatched = 'Unmatched';
SET @returnCode = CAST(@CAReturnCode AS INT);
我将收到错误:Msg 245,Level 16,State 1,Line 21 将varchar值“1”转换为数据类型int时,转换失败。
此错误发生在我显示的代码段的最后一行:
SET @returnCode = CAST(@CAReturnCode AS INT);
这是由同事写的代码,据说对他有用。我不得不解决一些错误,但我不能调试这个。我知道很多人会创建一个dbo.split函数?我不知道这个选项在这种情况下是否会对我有所帮助。我已经尝试将@returnCode设置为varchar并在@CAReturnCode上删除CAST。因此,调试器将使其超过该行,但会引发其余代码的问题。我假设我是如何投射@CAReturnCode的?任何帮助将不胜感激。
答案 0 :(得分:2)
问题是@CAReturnCode包含非数字字符。
-- Msg 245, Level 16, State 1, Line 21 Conversion failed when converting the varchar value '"1"' to data type int.
请参阅外部单引号是错误消息的格式,但内部双引号位于@CAReturnCode值中。所以这里的解决方案是确保变量在转换之前只包含数字字符。如果双引号是唯一的可能性,你可以像这样做一个快速而又脏的修复:
set @returnCode = cast(replace(@CAReturnCode, '"', '') as int)
如果有更多可能性,您可以进行多次REPLACE调用,或者您可以构建一个更好的字符修剪功能,它将自动删除您指定的所有字符。