天天看点

SqlServer 将纯数字的时间转换为DateTime

SqlServer 将纯数字的时间转换为DateTime

由于数据库存的是整个字符串组到一起了,C#代码是这个样子的。

复制代码

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中进行转换需要是有标准的 例如/ : 等符号。那么我们就进行截取吧。

CONVERT(datetime, left(q.YL01,4)+'-'+SUBSTRING(q.YL01,5,2)+'-'

+SUBSTRING(q.YL01,7,2))>=DATEADD(MM,-3,getdate())            

最后就完事了。

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           

原文地址

https://www.cnblogs.com/ZaraNet/p/10756048.html
下一篇: SQL常用语句