SqlServer 將純數字的時間轉換爲DateTime

因爲數據庫存的是整個字符串組到一塊兒了,C#代碼是這個樣子的。sql

public static string time(DateTime dt)
        {
            return dt.Year.ToString() + ((Convert.ToInt32(dt.Month) < 10) ? "0" + dt.Month.ToString() : dt.Month.ToString()) + ((Convert.ToInt32(dt.Day) < 10) ? "0" + dt.Day.ToString() : dt.Day.ToString()) + ((Convert.ToInt32(dt.Hour) < 10) ? "0" + dt.Hour.ToString() : dt.Hour.ToString()) + ((Convert.ToInt32(dt.Minute) < 10) ? "0" + dt.Minute.ToString() : dt.Minute.ToString()) + ((Convert.ToInt32(dt.Second) < 10) ? "0" + dt.Second.ToString() : dt.Second.ToString());
        }

在sqlserver中存儲的實際值是:20190416124941。那麼直接轉換?數據庫

因此在sqlserver中查詢的時候咱們要進行轉化,由於在mssql中進行轉換須要是有標準的 例如/ : 等符號。那麼咱們就進行截取吧。sqlserver

CONVERT(datetime, left(q.YL01,4)+'-'+SUBSTRING(q.YL01,5,2)+'-'
            +SUBSTRING(q.YL01,7,2))>=DATEADD(MM,-3,getdate()) 

最後就完事了。spa

SELECT distinct TOP 1 z.*,
        MAX(CASE WHEN S.Col_name_en = 'dwtt_crack_act' THEN S.Actual ELSE null END) as [斷裂數量實績值],
    MAX(CASE WHEN S.Col_name_en = 'dwtt_dft_act' THEN S.Actual ELSE null END) as [撓度實績值],q.YL01 FROM
(SELECT Z.Entrustment,z.Test_item_code,Z.sample_no
            FROM HB_M0LMZL Z
            WHERE TEST_ITEM_Code = 'QF' 
            GROUP BY Z.Entrustment,Z.Test_item_code,Z.Sample_no
            HAVING MAX(CASE WHEN z.col_name_en = 'cast_no' THEN z.Actual ELSE null END) = ''
) as Z LEFT JOIN HB_M0LMQ1 Q ON Q.Sample_lot_no = Z.Entrustment AND Q.Test_item_code 
    = Z.Test_item_code AND Z.Sample_no = Q.Sample_no LEFT JOIN HB_LMM0SJ S ON S.Test_item_code 
        = Z.Test_item_code AND S.Sample_no = Z.Sample_no AND S.Entrustment = Z.Entrustment
         WHERE CONVERT(datetime, left(q.YL01,4)+'-'+SUBSTRING(q.YL01,5,2)+'-'
            +SUBSTRING(q.YL01,7,2))>=DATEADD(MM,-3,getdate()) 
            GROUP BY Z.Entrustment,Z.Test_item_code,Z.Sample_no,q.YL01
            ORDER BY Q.YL01
相關文章
相關標籤/搜索