将Varchar列转换为Datetime

时间:2013-09-10 16:45:29

标签: sql sql-server tsql

我的任务是计算NUMBERS列和SHIP_DATES列中月和会计年度的差异。在计算之前,我无法从NUMBERS列(NUMBER_MONTH列)和(NUMBER_FY)中的字符串转换日期或时间。

有人可以看一下吗?基本上,我遇到的问题是我不能SHIP_DATE_MONTH减去NUMBER_MONTHSHIP_DATE_FY减去NUMBER_FY

  • NUMBERSvarchar。格式为SSSYYMMFFFFFF,其中

    • SSS是商店电台,
    • YY是会计年度,
    • MM是月份,
    • FFFFFF是频率
  • SHIP_DATESdatetime

  • ID是int。

这是我的代码:

CREATE TABLE #TEMP
(
  NUMBERS    VARCHAR (20),
  SHIP_DATES DATETIME,
  ID         INT
)

INSERT INTO #TEMP VALUES ( 'ABC1006000046' , '6/5/2010'  , '123' )
INSERT INTO #TEMP VALUES ( 'ABC1006000046' , '7/15/2013' , '123' )
INSERT INTO #TEMP VALUES ( 'CDS0809000059' , '9/8/2008'  , '124' )
INSERT INTO #TEMP VALUES ( 'CDS0809000059' , '1/31/2013' , '124' )

SELECT SUBSTRING(NUMBERS, 6, 2)     AS NUMBER_MONTH,
       SUBSTRING(NUMBERS, 4, 2)     AS NUMBER_FY,
       DATEPART (MONTH, SHIP_DATES) AS SHIP_DATE_MONTH,
       DATEPART (YEAR, SHIP_DATES)  AS SHIP_DATE_FY,
       ID
INTO #TEMP1
FROM #TEMP

--calculate the difference in month and fiscal year
SELECT DATEDIFF( YEAR  , NUMBER_FY    , SHIP_DATE_FY    ) AS DIFF_YEAR  ,
       DATEDIFF( MONTH , NUMBER_MONTH , SHIP_DATE_MONTH ) AS DIFF_MONTH ,
       ID
FROM #TEMP1

这是我收到的错误消息:

Conversion failed when converting date and/or time from character string.

请注意,这是转换为日期时间的方法,但我还没弄清楚如何让它工作:

CONVERT(VARCHAR , SHIP_DATES , 101 ) AS 'MM/DD/YYYY'

3 个答案:

答案 0 :(得分:1)

当你调用DATEDIFF时,第二个和第三个参数的类型为DateTime,你传递第二个参数的字符串和第三个参数的整数。

我认为(如果我理解你要做什么)你应该将字符串转换为数字,摆脱DATEDIFF并进行常规的减号操作。

评论后补充: 要将nvarcahr强制转换为int,您可以像这样更改代码:

SELECT 
    CAST(SUBSTRING(NUMBERS, 6, 2) AS BIGINT)    AS NUMBER_MONTH,
    CAST(SUBSTRING(NUMBERS, 4, 2) AS BIGINT)    AS NUMBER_FY,
    DATEPART (MONTH, SHIP_DATES) AS SHIP_DATE_MONTH,
    DATEPART (YEAR, SHIP_DATES)  AS SHIP_DATE_FY,
        ID
INTO #TEMP1
FROM #TEMP

答案 1 :(得分:0)

我会在这些方面尝试更多的东西:

CREATE TABLE #TEMP 
    (NUMBERS VARCHAR (20), SHIP_DATES_A DATETIME, SHIP_DATES_B DATETIME, ID INT)

然后进行测试:

INSERT INTO TEMP VALUES ('ABC1006000046', '6/5/2010','7/15/2013', '123')
INSERT INTO TEMP VALUES ('CDS0809000059', '9/8/2008','1/31/2013', '124')

然后这个查询:

select NUMBERS,SHIP_DATES_A,SHIP_DATES_B,ID,
    DATEDIFF(month,ship_dates_a,ship_dates_b)
from temp

答案 2 :(得分:0)

为什么不这样做?

CREATE TABLE #TEMP
(
  NUMBERS    VARCHAR (20),
  SHIP_DATES DATETIME,
  ID         INT
)

INSERT INTO #TEMP VALUES ( 'ABC1006000046' , '6/5/2010'  , '123' )
INSERT INTO #TEMP VALUES ( 'ABC1006000046' , '7/15/2013' , '123' )
INSERT INTO #TEMP VALUES ( 'CDS0809000059' , '9/8/2008'  , '124' )
INSERT INTO #TEMP VALUES ( 'CDS0809000059' , '1/31/2013' , '124' )

SELECT  CAST('20' + SUBSTRING(NUMBERS, 6, 2) + '-' + SUBSTRING(NUMBERS, 4, 2) + '-01'     AS DATE) AS NumsDate,
SHIP_DATES
INTO #TEMP2      
FROM #TEMP

SELECT 
    DATEDIFF(M, NumsDate, SHIP_DATES) AS Diff_In_Months,
    DATEDIFF(YEAR, NumsDate, SHIP_DATES) AS Diff_In_Years  
FROM 
    #TEMP2