将varchar(50)转换为datetime并填充表的其余部分

时间:2014-01-02 05:58:43

标签: sql sql-server sql-server-2012

我正在处理数据仓库,在数据模型中还有一个维度表dim.date,需要从excel表填充。

这是表结构

CREATE TABLE timeme 
  ( 
     datekey             INT IDENTITY NOT NULL, 
     fulldate            VARCHAR(50), 
     englishdayname      VARCHAR(20), 
     englishmonthname    VARCHAR(20), 
     daynumberofthemonth INT, 
     daynumbarofyear     INT, 
     weeknumberofyear    INT, 
     calenderquater      INT, 
     calenderyear        INT 
  ) 

INSERT INTO timeme 
            (fulldate) 
VALUES     ('03-13-2013-02:41:38'), 
            ('03-13-2013-02:39:50'), 
            ('03-13-2013-02:53:15'), 
            ('03-13-2013-02:59:47') 

这是我试过的

-- select * from timeme

--update timeme set fulldate= cast(left(fulldate, 10)+ ' ' +replace(substring(fulldate, 12, 12), '.', ':') as datetime)-- but it should be  2013-03-13 02:41:38.000

UPDATE timeme 
SET    englishdayname = Datename(dw, fulldate), 
       englishmonthname = Datename(mm, fulldate), 
       daynumberofthemonth = Datepart(d, fulldate) 

Update timeme 
SET daynumbarofyear -- this i didnt get rest how to populate

有人可以帮我填充整个表格

1 个答案:

答案 0 :(得分:1)

你在找这个吗?

UPDATE timeme
   SET fulldate = SUBSTRING(fulldate, 7, 4) + '-' + LEFT(fulldate, 5) + ' ' + RIGHT(fulldate, 8);

UPDATE timeme
   SET englishdayname      = DATENAME(dw, CAST(fulldate AS DATE)),
       englishmonthname    = DATENAME(mm, CAST(fulldate AS DATE)),
       daynumberofthemonth = DATEPART(dd, CAST(fulldate AS DATE)),
       daynumbarofyear     = DATEPART(dy, CAST(fulldate AS DATE)),
       weeknumberofyear    = DATEPART(ww, CAST(fulldate AS DATE)), -- or isoww instead of ww
       calenderquater      = DATEPART(qq, CAST(fulldate AS DATE)),
       calenderyear        = DATEPART(yy, CAST(fulldate AS DATE));

结果:

| DATEKEY |            FULLDATE | ENGLISHDAYNAME | ENGLISHMONTHNAME | DAYNUMBEROFTHEMONTH | DAYNUMBAROFYEAR | WEEKNUMBEROFYEAR | CALENDERQUATER | CALENDERYEAR |
|---------|---------------------|----------------|------------------|---------------------|-----------------|------------------|----------------|--------------|
|       1 | 2013-03-13 02:41:38 |      Wednesday |            March |                  13 |              72 |               11 |              1 |         2013 |
|       2 | 2013-03-13 02:39:50 |      Wednesday |            March |                  13 |              72 |               11 |              1 |         2013 |
|       3 | 2013-03-13 02:53:15 |      Wednesday |            March |                  13 |              72 |               11 |              1 |         2013 |
|       4 | 2013-03-13 02:59:47 |      Wednesday |            March |                  13 |              72 |               11 |              1 |         2013 |

这是 SQLFiddle 演示