esse problema surge porque o SQL Server não executa comparações em caracteres convertidos em inteiros de maneira idêntica. Em meu teste, descobri que algumas comparações de caracteres convertidos, como o ponto de exclamação, retornarão erros de conversão de tipo, enquanto outras comparações de caracteres convertidos, como o espaço, serão determinadas como fora do intervalo.
Este código de amostra testa os diferentes cenários possíveis e apresenta uma solução usando instruções REPLACE aninhadas. O REPLACE determina se há algum caractere na string que não seja numeral ou barra e, se houver, o comprimento da string será maior que zero, indicando assim que existem caracteres 'ruins' e a data é inválida .
assim
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',''),'/',''),' ','+'))) --replace space with a + to avoid empty string
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',''),'/',''),' ','+'))) --replace space with a + to avoid empty string
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',''),'/',''),' ','+'))) --replace space with a + to avoid empty string
resultado
--Output
--12/10/2012: Passed Test
--Number of characters in 12/10/2012 that are not numerals or a slash (0 means the date is valid; all values greater than 0 indicate a problem): 0
--Msg 245, Level 16, State 1, Line 4
--Conversion failed when converting the varchar value '!0' to data type int.
--Number of characters in 12/!0/2012 that are not numerals or a slash (0 means the date is valid; all values greater than 0 indicate a problem): 1
--12/ /2012: Failed Test
--Number of characters in 12/ /2012 that are not numerals or a slash (0 means the date is valid; all values greater than 0 indicate a problem): 2
---------------------------------------x----x---x
- this happens because sql sometimes doesn't recognize dd/mm/yyyy format
- so we should always check if the input string is a valid date or not and the accordingly convert it to mm/dd/yyyy and so , i have shown below how it can be done, i have created a function to rearrange in mm/dd/yyyy from dd/mm/yyyy
select case when isdate('yourdate')=1 then CAST('yourdate' AS datetime)
else (select * from dbo.fn_convertdate(yourdate))
Create function dbo.fn_convertdate( @Stringdate nvarchar(29))
RETURNS @output TABLE(splitdata NVARCHAR(MAX)
)
Begin
Declare @table table(id int identity(1,1), data varchar(255))
Declare @firstpart nvarchar(255)
Declare @tableout table(id int identity(1,1), data varchar(255))
Declare @Secondpart nvarchar(255)
Declare @Thirdpart nvarchar(255)
declare @date datetime
insert into @table
select * from dbo.fnSplitString(@Stringdate,'/')
select @firstpart=data from @table where id=2
select @Secondpart=data from @table where id=1
select @Thirdpart=data from @table where id=3
set @date=@firstpart+'/'+@Secondpart+'/'+@Thirdpart
insert into @output(splitdata) values(
@date)
return
End