简体   繁体   English

SQL将日期dmmyyyy和ddmmyy转换为yyyy-mm-dd

[英]SQL convert date dmmyyyy and ddmmyy to yyyy-mm-dd

I have the following problem. 我有以下问题。 I have some dates with the following format '15122019' and I need it in this format 2019-12-15, which I already solved it in the following way. 我有一些日期格式为'15122019'的日期,我需要此格式为2019-12-15,我已经用以下方式解决了。

select convert (date, Stuff(Stuff('15122018',5,0,'.'),3,0,'.'),104)

The real problem is when the dates come like this '3122019' the conversion can not be done because the length is shorter. 真正的问题是,当日期像这样的“ 3122019”时,由于长度较短,无法进行转换。 Is ther e another way to do it? 还有另一种方法吗? I've been trying to solve it for several hours. 我已经尝试解决了几个小时。 And another question, can this query be parameterized? 还有一个问题,可以将此查询参数化吗?

Try this: 尝试这个:

 DECLARE @date VARCHAR(20)
 SET @date ='3122019'

 IF(LEN(@date) = 8)
 BEGIN  
    SET @date = Stuff(Stuff(@date,5,0,'.'),3,0,'.');
    SELECT CONVERT(DATE, @date , 103);
 END
 ELSE IF(LEN(@date) = 7) 
 BEGIN

    SET @date = Stuff(Stuff(@date,4,0,'.'),2,0,'.');
    IF(ISDATE(@date)=1)
    BEGIN
        SELECT CONVERT(DATE, @date , 103);          
    END    
    ELSE
    BEGIN
        SET @date = Stuff(Stuff(@date,4,0,'.'),3,0,'.');    
            SELECT CONVERT(DATE, @date , 103);
    END
 END
 ELSE IF(LEN(@date) = 6)
 BEGIN
     SET @date = Stuff(Stuff(@date,3,0,'.'),2,0,'.');
     SELECT CONVERT(DATE, @date , 103);
 END

Such conversation can be achieved by: 可以通过以下方式实现此类对话:

  • Casting integer value to DATE using intermediate FORMAT transformation to a recognizable for conversation string pattern. 使用中间的FORMAT转换将整数值转换为DATE,以转换为可识别的对话字符串模式。
    • style 105 applied to match the input as dd-mm-yyyy 应用样式105以匹配输入为dd-mm-yyyy
    • style 05 to match dd-mm-yy 样式05以匹配dd-mm-yy

SQL: SQL:

-- input format: dmmyyyy
SELECT CONVERT(DATE, FORMAT(3012019, '##-##-####'), 105)
-- result: 2019-01-03

-- input format: dmmyy
SELECT CONVERT(DATE, FORMAT(30119, '##-##-##'), 05)
-- result: 2019-01-03

This will work fine with a single (and double) digit day number, however, it indeed requires a double-digit month 这对于单数(和两位数)的天数可以很好地工作,但是,确实需要两位数的月份

You can add 0 to the left and take 8 chars with right . 您可以添加0到左侧,并采取8个字符用right like RIGHT('0'+'15122018',8) . 就像RIGHT('0'+'15122018',8) it work with 15122018 and 3122018 它适用于15122018和3122018

select convert (date, Stuff(Stuff( RIGHT('0'+'15122018',8) ,5,0,'.'),3,0,'.'),104)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM