在SQL中将字符串格式化为日期?

时间:2012-02-01 18:15:05

标签: sql sql-server string datetime varchar

我有这个存储过程:

ALTER Procedure [dbo].[GetWebinars]
(
    @GroupingCode varchar(max) = 'AVM',
    @ItemNumber varchar(max) out,
    @Title varchar(max) out,
    @SubTitle varchar(max) out,
    @ShortDescription varchar(max) out,
    @LongDescription varchar(max) out,
    @ShortImageUrl varchar(max) out,
    @MedImageUrl varchar(max) out,
    @LgImageUrl varchar(max) out,
    @GroupCode varchar(max) out,
    @StartDate varchar(max) out
)
AS
    select 
    @GroupingCode = prdtemp.groupingcode,
    @ItemNumber = prd.itemnumber,    
    @Title = t.brochuredesc,
    @SubTitle = prdtemp.SubTitle,
    @ShortDescription = prdtemp.shortdescription,
    @LongDescription = prdtemp.longdescription,
    @ShortImageUrl = prdtemp.SmallImagePath,
    @MedImageUrl  = prdtemp.MediumImagePath,
    @LgImageUrl = prdtemp.LargeImagePath,
    @GroupCode = prd.GroupCode,
    @StartDate = s.StartDate

    from pryor_producttemplate prdtemp
        inner join pryor_prdItmmst prd
        on prdtemp.groupingcode  = prd.groupcode
        inner join pryor_topics t
        on prd.itemnumber =  t.topiccode
        inner join Pryor_Schedule s
        on t.TopicCode = s.topiccode    

    where prdtemp.groupingcode=@GroupingCode and t.country = 'U.S.A'

我的问题是@StartDate是DB中的var char。如何将其转换为适当的日期以呈现为D / M / YY?

1 个答案:

答案 0 :(得分:0)

使用convert函数将字符串转换为日期时间:

@StartDate = convert(datetime, s.StartDate, 120)

第三个参数指定日期格式。值120例如指定人类友好的ISO 8601格式。有关所有支持的日期格式,请参阅CAST and CONVERT的参考。

当然,您还必须更改变量的类型:

@StartDate datetime out