我遇到了同样的问题,并确定出现此问题是因为SQL Server不会对以相同方式转换为整数的字符执行比较。在我的测试中,我发现转换后的字符的某些比较(例如感叹号)将返回类型转换错误,而转换后的字符的其他比较(例如空格)将被确定超出范围。
此示例代码测试了各种可能的情况,并使用嵌套的REPLACE语句提供了一种解决方案。REPLACE确定字符串中是否有任何非数字或斜杠的字符,如果存在,则字符串的长度将大于零,从而指示存在“坏”字符且日期无效。
DECLARE @str varchar(10)
SET @str = '12/10/2012'
IF convert(int, substring(@str,4,2)) <= 31 AND convert(int, substring(@str,4,2)) >= 1
PRINT @str+': Passed Test'
ELSE PRINT @str+': Failed Test'
GO
DECLARE @str varchar(10)
SET @str = '12/10/2012'
PRINT 'Number of characters in ' + @str + ' that are not numerals or a slash (0 means the date is valid; all values greater than 0 indicate a problem): ' + convert(varchar(5),len(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(@str,'0',''),'1',''),'2',''),'3',''),'4',''),'5',''),'6',''),'7',''), '8',''),'9',''),'/',''),' ','+')))
PRINT ''
GO
DECLARE @str varchar(10)
SET @str = '12/!0/2012'
IF convert(int, substring(@str,4,2)) <= 31 AND convert(int, substring(@str,4,2)) >= 1
PRINT @str+': Passed Test'
ELSE PRINT @str+': Failed Test'
GO
DECLARE @str varchar(10)
SET @str = '12/!0/2012'
PRINT 'Number of characters in ' + @str + ' that are not numerals or a slash (0 means the date is valid; all values greater than 0 indicate a problem): ' + convert(varchar(5),len(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(@str,'0',''),'1',''),'2',''),'3',''),'4',''),'5',''),'6',''),'7',''), '8',''),'9',''),'/',''),' ','+')))
PRINT ''
GO
DECLARE @str varchar(10)
SET @str = '12/ /2012'
IF convert(int, substring(@str,4,2)) <= 31 AND convert(int, substring(@str,4,2)) >= 1
PRINT @str+': Passed Test'
ELSE PRINT @str+': Failed Test'
GO
DECLARE @str varchar(10)
SET @str = '12/ /2012'
PRINT 'Number of characters in ' + @str + ' that are not numerals or a slash (0 means the date is valid; all values greater than 0 indicate a problem): ' + convert(varchar(5),len(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(@str,'0',''),'1',''),'2',''),'3',''),'4',''),'5',''),'6',''),'7',''), '8',''),'9',''),'/',''),' ','+')))
输出: