sexta-feira, 15 de junho de 2012

Explicitly set the length of the variables

I was working on a function wich should return me a due date for a billing system, when all of a suden, an error show up: I cannot convert a date in string to a datetime. An excerpt of the code is:


declare @mes varchar = cast(month(getdate()) as varchar),
@ano varchar = cast(year(getdate()) as varchar),
@dia varchar = cast(day(getdate()) as varchar);



select convert(smalldatetime, @ano + '.'  + @mes + '.' + @dia  , 102 ) -- Error here!!!


The result string from  @ano + '.'  + @mes + '.' + @dia was  '2.6.15' (I am using the ANSI format, i.e. 102). I could figure out that issuing a simple select statement:
select @ano + '.'  + @mes + '.' + @dia, cast(year(getdate()) as varchar) 

The solution: explicitly set the length of the variables. Look down here:

declare @mes varchar(2) = cast(month(getdate()) as varchar),
@ano varchar(4) = cast(year(getdate()) as varchar),
@dia varchar(2) = cast(day(getdate()) as varchar);

Finally, the goes (back) on...

Nenhum comentário:

Postar um comentário