The answer - don't use implicit conversions. And read BOL about the CASE
expression and how it determines the datatype of the returned value. Below
is a quick script that demonstrates two much easier ways to accomplish the
task.
declare @test datetime
set @test = '20050115'
select '0' + cast(datepart(day, @test) as varchar(2))
,RIGHT('0' + cast(datepart(day, @test) as varchar(2)), 2)
,convert(char(2), @test, 4)
set @test = '20050102'
select '0' + cast(datepart(day, @test) as varchar(2))
,RIGHT('0' + cast(datepart(day, @test) as varchar(2)), 2)
,convert(char(2), @test, 4)
[quoted text, click to view] "Robert Richards via SQLMonster.com" <forum@SQLMonster.com> wrote in message
news:79f6ea5cca2a4a679dea642da149fc43@SQLMonster.com...
> I am trying to return a two character result for the day number and was
> wondering why I get a one character day returned in Statement A, and a two
> character result in Statement B?
>
> declare @day varchar(2)
>
> --Statement A:
> set @day = case len(day(getdate()))
> when 1 then cast('0' + cast (day(getdate()) as varchar(1)) as
> varchar(2))
> else
> day(getdate())
> end
> print @day
>
> --the result is a one character day, if the date was February 7, 2005, the
> result = 7
>
> --Statement B:
> if len(day(getdate())) = 1
> set @day = '0' + cast (day(getdate()) as varchar(1))
> else
> set @day = day(getdate())
>
> print @day
>
> --the result is a two character day, if the date was February 7, 2005, the
> result = 07
>
> --
> Message posted via
http://www.sqlmonster.com