更改字符串以自定义SQL上的格式

时间:2014-11-12 05:31:34

标签: sql

我在表格上保存了字符串格式。格式如下 -

`11/Apr/2014 2:30:00 PM-11/Apr/2014 4:00:00 PM`. 

使用此格式我想在运行存储过程时返回自定义格式。格式应为 -

`9.00 AM To 10.00 AM`.

这就是我正在尝试的:

SUBSTRING(LeaveManagement.EmployeeLeaveTransaction.Period, 12, 5) +
SUBSTRING(LeaveManagement.EmployeeLeaveTransaction.Period, 20, 3) + 
' To ' + 
SUBSTRING(LeaveManagement.EmployeeLeaveTransaction.Period, 36, 5) +
SUBSTRING(LeaveManagement.EmployeeLeaveTransaction.Period, 44, 3)

但如果原始字符串有

,则返回错误的格式

11/Apr/2014 12:30:00 PM-11/Apr/2014 4:00:00 PM

任何人都可以帮我这样做。我正在尝试使用此查询

2 个答案:

答案 0 :(得分:0)

此查询有助于在 SQL SERVER 中获得预期结果。

DECLARE @Date AS VARCHAR(100)

SET @Date = '11/Apr/2014 1:30:00 PM-11/Apr/2014 2:00:00 PM'

SELECT SUBSTRING(@Date, CHARINDEX(' ', @Date), CHARINDEX('-', @Date) - CHARINDEX(' ', @Date)) 
        + ' To ' 
        + Reverse(Substring(REVERSE(@Date), 0, CHARINDEX('/', REVERSE(@Date)) - 5))

使用此查询:

SUBSTRING(LeaveManagement.EmployeeLeaveTransaction.Period, 
  CHARINDEX(' ', LeaveManagement.EmployeeLeaveTransaction.Period), 
    CHARINDEX('-', LeaveManagement.EmployeeLeaveTransaction.Period) 
    - CHARINDEX(' ', LeaveManagement.EmployeeLeaveTransaction.Period)) 
+ ' To ' 
+ Reverse(Substring(REVERSE(LeaveManagement.EmployeeLeaveTransaction.Period), 
    0, CHARINDEX('/', REVERSE(LeaveManagement.EmployeeLeaveTransaction.Period)) - 5))

答案 1 :(得分:0)

SEELCT substr(COL_NAME,instr(COL_NAME,' ',1,1)+1,5)||
       substr(COL_NAME,instr(COL_NAME,' ',1,2),3)  ||
       ' TO '                                      ||
       substr(COL_NAME,instr(COL_NAME,' ',1,3),5)  ||
       substr(COL_NAME,instr(COL_NAME,' ',1,4),3)  
FROM   table_name