简体   繁体   English

SQL-转换为日期

[英]SQL - Convert to date

I have a numeric column in SQL which I need to convert to a date. 我在SQL中有一个数字列,我需要将其转换为日期。 The field is currently coming into the database as: "20181226.00000" . 该字段当前进入数据库: "20181226.00000"

I only need to the characters before the " . " . 我只需要在" . "之前的字符。 So i did a SUBSTRING - CHARINDEX looking for anything before the " . " . 所以我做了一个SUBSTRING - CHARINDEX寻找在" . "之前的东西。 I then did a cast as NVARCHAR . 然后,我将其转换为NVARCHAR

Now I'm getting 20181226 but I want this date field to populate like: "MM/DD/YYYY" . 现在我得到20181226但我希望此日期字段填充为: "MM/DD/YYYY"

My current SQL is: 我当前的SQL是:

CONVERT(VARCHAR(10),SUBSTRING(CAST('MYFIELD' AS NVARCHAR(50)) ,0, CHARINDEX('.', 'MYFIELD' , 0)),101)

只需将101更改为103

CONVERT(VARCHAR(10),SUBSTRING(CAST('MYFIELD' AS NVARCHAR(50)) ,0, CHARINDEX('.', 'MYFIELD' , 0)),101)

The easiest way is to convert it to what it actually is, a date , and then back to a varchar using the right style. 最简单的方法是将其转换为实际的date ,然后使用正确的样式将其转换回varchar

SELECT convert(varchar(max), convert(date, substring(convert(varchar(max), nmuloc), 1, charindex('.', convert(varchar(max), nmuloc)) - 1)), 101)
       FROM elbat;

I wasn't sure if it's a number or a string. 我不确定是数字还是字符串。 If it's a string you don't need the convert(varchar(max), nmuloc) s. 如果是字符串,则不需要convert(varchar(max), nmuloc)

However a side note: You should not store dates as numbers or strings. 但是请注意:您不应该将日期存储为数字或字符串。 Use an appropriate data type like date . 使用适当的数据类型,例如date

Or you could achieve it like this. 或者您可以像这样实现它。

declare @v_value numeric(18,5)=20181226.00000

SELECT SUBSTRING(CAST(CAST(@v_value AS INT) AS VARCHAR),5,2)+'/'+SUBSTRING(CAST(CAST(@v_value AS INT) AS VARCHAR),7,2)+'/'+SUBSTRING(CAST(CAST(@v_value AS INT) AS VARCHAR),1,4) as V_OUTPUT

--Output
/*
V_OUTPUT
------------------
12/26/2018
*/

Best Regards, 最好的祝福,

Will

First we have convert to varchar and then Date format 首先,我们先转换为varchar,然后转换为Date格式

SELECT  CONVERT(varchar, CAST(CAST('20181206.00000' as VARCHAR(8)) AS DATE), 103); dd/mm/yyyy

SELECT  CONVERT(varchar, CAST(CAST('20181206.00000' as VARCHAR(8)) AS DATE), 101); mm/dd/yyyy 

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

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