3
respostas

Erro ao gerar o script de carga inicial .

Quando eu gero a estrutura das tabelas no banco de dados, funciona perfeitamente, mas quando eu gero o script de carga inicial aparece essas mensagens.

(0 row(s) affected) "Essa funcionou perfeitamente".

Mas a partir da linha 17 em diante acontece esse erro.!! Msg 242, Level 16, State 3, Line 17 A conversão de um tipo de dados nvarchar em um tipo de dados datetime resultou em um valor fora do intervalo.

3 respostas

Olá, Eduardo!

Se precisar converter sua entrada, você pode tentar examinar o CONVERT método. Sintaxe é

CONVERT(VARCHAR,@your_date_Value,103)

CONVERT(VARCHAR, '12/30/2013', 103)

O final 103 é o formato datetime.

*Certifique-se de que a data realmente existe! * Exemplo:

31 de setembro de 2015 não existe.

EXEC dbo.SearchByDateRange @Start = '20150901' , @End = '20150931' Portanto, isso falha com a mensagem:

Error converting data type varchar to datetime. Para consertar, insira uma data válida:

EXEC dbo.SearchByDateRange @Start = '20150901' , @End = '20150930' E ele executa muito bem.

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

Tinha uma linha problemática com string de data '19610010' (formato: AAAAMMDD) que causou o erro 'A conversão de um tipo de dados nvarchar em um tipo de dados datetime resultou em um valor fora do intervalo'. SELECT CONVERT (datetime, 'yourdate') FROM [yourtable] WHERE ISDATE ('yourdate') = 1

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software