SQL Custom Function--fixed format character turn time type

Source: Internet
Author: User
Tags local time

Met a German customer, their time format is JJJJ-TT-DD HH:MM:SS, the program in accordance with this format to insert time into the database, but the SQL comes with the conversion function convert, the cast process error, the online search has said with convert, Cast can be converted directly, but this customer's machine is not, there is no way to write a conversion function for everyone to refer to:

Because the GetDate method cannot be used directly inside a custom function, a small function that gets local time is created first:

Create view v_getdate as select getdate() as Now_ Date

Then the conversion function:

1 CREATE  FUNCTIONToDateTime (@DateStr varchar( -))2 RETURNS datetime 3  as  4 BEGIN 5 Declare @OutTime datetime6 Select @OutTime=Now_date fromv_getdate7 if(Len(@DateStr)< -)8   Set @DateStr=substring(@DateStr+'00:00:00',1, -)9 Set @OutTime=DateAdd( Year,0- Year(@OutTime)+cast(substring(@DateStr,1,4) as int),@OutTime)Ten Set @OutTime=DateAdd(Month,0-Month(@OutTime)+cast(substring(@DateStr,6,2) as int),@OutTime) One Set @OutTime=DateAdd( Day,0- Day(@OutTime)+cast(substring(@DateStr,9,2) as int),@OutTime) A Set @OutTime=DateAdd(Hour,0-DATEPART(HH,@OutTime)+cast(substring(@DateStr, A,2) as int),@OutTime) - Set @OutTime=DateAdd(Minute,0-DATEPARTN@OutTime)+cast(substring(@DateStr, the,2) as int),@OutTime) - Set @OutTime=DateAdd(Second,0-DATEPARTS@OutTime)+cast(substring(@DateStr, +,2) as int),@OutTime) the return @OutTime - END

Invocation Example: SELECT dbo. ToDateTime (' 2014-04-05 06:07:08 ')

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.