문제

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