将特定字符串(0716_F_Frndy)转换为日期(2016年7月1日)

时间:2017-02-06 17:23:37

标签: tsql

如何将以下varchar转换为日期?

自:

0716_F_Frndy,
1116_F_Iniends,
0416_F_Fuds,
0117_F_NeYears,
0816_F_Wiether,
1215_F_Xmerral,
1016_F_HapyFingers,
0616_F_Ginglish,
1216_F_Xmft,
0116_F_Ners,
1015_F_Hangers,
0316_F_Sp,
0216_F_Le,
0916_F_Back,
0516_F_Shar

1-july-2016
1-november-2016
1-april-2016
1-jan-2017
1-aug-2016
1-dec-2015

...

1 个答案:

答案 0 :(得分:0)

Declare @YourTable table (Col varchar(50))
Insert Into @YourTable values
('0716_F_Frndy'),
('1116_F_Iniends'),
('0416_F_Fuds'),
('0117_F_NeYears'),
('0816_F_Wiether'),
('1215_F_Xmerral'),
('1016_F_HapyFingers'),
('0616_F_Ginglish'),
('1216_F_Xmft'),
('0116_F_Ners'),
('1015_F_Hangers'),
('0316_F_Sp'),
('0216_F_Le'),
('0916_F_Back'),
('0516_F_Shar')

Select Col
      ,AsDate           = cast(Stuff(Left(col,4),3,0,'/01/') as date)
      ,AsFormatted      = Format(cast(Stuff(Left(col,4),3,0,'/01/') as date),'d-MMMM-yyyy')
      ,AsFormattedShort = Format(cast(Stuff(Left(col,4),3,0,'/01/') as date),'d-MMM-yyyy')
 From  @YourTable

返回

Col                 AsDate      AsFormatted         AsFormattedShort
0716_F_Frndy        2016-07-01  1-July-2016         1-Jul-2016
1116_F_Iniends      2016-11-01  1-November-2016     1-Nov-2016
0416_F_Fuds         2016-04-01  1-April-2016        1-Apr-2016
0117_F_NeYears      2017-01-01  1-January-2017      1-Jan-2017
0816_F_Wiether      2016-08-01  1-August-2016       1-Aug-2016
1215_F_Xmerral      2015-12-01  1-December-2015     1-Dec-2015
1016_F_HapyFingers  2016-10-01  1-October-2016      1-Oct-2016
0616_F_Ginglish     2016-06-01  1-June-2016         1-Jun-2016
1216_F_Xmft         2016-12-01  1-December-2016     1-Dec-2016
0116_F_Ners         2016-01-01  1-January-2016      1-Jan-2016
1015_F_Hangers      2015-10-01  1-October-2015      1-Oct-2015
0316_F_Sp           2016-03-01  1-March-2016        1-Mar-2016
0216_F_Le           2016-02-01  1-February-2016     1-Feb-2016
0916_F_Back         2016-09-01  1-September-2016    1-Sep-2016
0516_F_Shar         2016-05-01  1-May-2016          1-May-2016