Hi I'm trying to create a user-defined function in SQL Server 2008, to convert dates from one format to another.

the date im using is missing the centuary i.e. 1610101 is 1961/01/01 and 213/02/15 is actually 2013/02/15.

i've searched this a good few websites for a solution but i cant see whats wrong with it.

create function Convert_Date(@Cdate Date)
returns Date
as
Begin
declare @return date
select @return = case @Cdate
when (LEFT(@Cdate,1) = 1) then convert(date,('19'+ CONVERT(VARCHAR(30), right(@Cdate,6))))
when (LEFT(@Cdate,1) = 2) then convert(date,('20'+ CONVERT(VARCHAR(30), right(@Cdate,6))))
return @return
end
有帮助吗?

解决方案

You want something like this:

CREATE FUNCTION Convert_Date(@Cdate DATE)
RETURNS DATE
AS
BEGIN

    DECLARE @return DATE

    SELECT @return = 
    (
        CASE LEFT(@Cdate,1) 
            WHEN '1' THEN CONVERT(DATE, ('19'+ CONVERT(VARCHAR(30), RIGHT(@Cdate,6)))) 
            WHEN '2' THEN CONVERT(DATE, ('20'+ CONVERT(VARCHAR(30), RIGHT(@Cdate,6))))
        END
    )

    RETURN @return
END

Your when statements should be the times when your result matches the case.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top