Using T-SQL DATEFROMPARTS to return NULL instead of throw error

前端 未结 1 1582
名媛妹妹
名媛妹妹 2021-01-24 10:14

Often I\'ve received dates in the form of some combination of integers or a single 8 digit integer. To convert them to a usable date I tried the DATEFROMPARTS function but when

相关标签:
1条回答
  • 2021-01-24 10:51

    I am not sure that I understood you right, but it might help:

    DECLARE @year VARCHAR(100)= '1993';
    DECLARE @month VARCHAR(100)= '12';
    DECLARE @day VARCHAR(100)= '01';
    
    
    SELECT CASE 
    WHEN  ISNUMERIC(@year) = 0 OR  ISNUMERIC(@month) = 0 OR  ISNUMERIC(@day) = 0 THEN NULL
    WHEN @year BETWEEN 1 AND 9999 AND (@month BETWEEN 1 AND 12 AND @day BETWEEN 1 AND 28
           OR @month IN(1, 3, 5, 7, 8, 10, 12) AND @day BETWEEN 1 AND 31
           OR @month IN(4, 6, 9, 11) AND @day BETWEEN 1 AND 30
           OR @month = 2 AND @day BETWEEN 1 and CASE WHEN NOT @year % 4 = 0 THEN 28 WHEN NOT @year % 100 = 0 THEN 29 WHEN NOT @year % 400 = 0 THEN 28 ELSE 29 END)
         THEN DATEFROMPARTS(@year, @month, @day) END;
    

    OUTPUT:

    1993-12-01

    DECLARE @year VARCHAR(100)= '1993';
    DECLARE @month VARCHAR(100)= 'Jan';
    DECLARE @day VARCHAR(100)= '01';
    
    
    SELECT CASE 
    WHEN  ISNUMERIC(@year) = 0 OR  ISNUMERIC(@month) = 0 OR  ISNUMERIC(@day) = 0 THEN NULL
    WHEN @year BETWEEN 1 AND 9999 AND (@month BETWEEN 1 AND 12 AND @day BETWEEN 1 AND 28
           OR @month IN(1, 3, 5, 7, 8, 10, 12) AND @day BETWEEN 1 AND 31
           OR @month IN(4, 6, 9, 11) AND @day BETWEEN 1 AND 30
           OR @month = 2 AND @day BETWEEN 1 and CASE WHEN NOT @year % 4 = 0 THEN 28 WHEN NOT @year % 100 = 0 THEN 29 WHEN NOT @year % 400 = 0 THEN 28 ELSE 29 END)
         THEN DATEFROMPARTS(@year, @month, @day) END;
    

    OUTPUT:

    NULL

    0 讨论(0)
提交回复
热议问题