SQL 转换为 mm/dd/yyyy 格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7248329/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 11:56:00  来源:igfitidea点击:

Converting to mm/dd/yyyy format

sqlsql-server-2008tsqlconverter

提问by Peter

I have a table called SF_Data and there is a column called IN_Date, ID the data looks like:

我有一个名为 SF_Data 的表,有一个名为 IN_Date 的列,ID 数据如下所示:

ID      IN_Date
1       9/8/2010
2       26/04/2011
3       20/09/2010

The datatatype of IN_Date is varchar(50).

IN_Date 的数据类型是 varchar(50)。

I am trying to convert the IN_Date to mm/dd/yyyy format. I tried doing this:

我正在尝试将 IN_Date 转换为 mm/dd/yyyy 格式。我尝试这样做:

Select convert(varchar,IN_Date,103) From dbo.SF_Data

But still the format doesn't change. Can anyone tell me where I am going wrong

但是格式仍然没有改变。谁能告诉我哪里出错了

回答by gbn

You need a convert to fix the data (to the correct datatype) beforeformatting...

格式化之前,您需要进行转换以修复数据(到正确的数据类型)...

Select
     convert(varchar,
         convert(date, IN_Date, 103),
     101)
from dbo.SF_Data

回答by Andomar

The 3rd parameter to converthas no meaning when converting from varcharto varchar. So per @marc_s' comment, you'd have to convert the varcharto a datetimeusing the 103 format, and then from datetimeto varcharspecifying the 101 format:

convertvarcharto转换时,第三个参数 to没有意义 varchar。因此,根据@marc_s 的评论,您必须使用 103 格式将 the 转换varchar为 a datetime,然后从datetimetovarchar指定 101 格式:

Select convert(varchar(12),convert(datetime,IN_Date,103),101) From dbo.SF_Data

For example:

例如:

select convert(varchar(12),convert(datetime,'31/12/2001',103),101)

prints 12/31/2001.

打印12/31/2001

See MSDN.

请参阅 MSDN。