I need to convert an existing date field in SQL to Month and Year and place them in a new table in two new columns

StackOverflow https://stackoverflow.com/questions/23659238

  •  22-07-2023
  •  | 
  •  

Question

I have tried this already

INSERT INTO #TempTable (year, month, day)
SELECT 
    DATEPART(yyyy, dtProc) as year,
    DATEPART(mm, dtProc) as month,
FROM DailyHist

But after this insertion I need to insert more fields which then create NULL values for my recently inserted month and year fields, using this SQL statement:

INSERT INTO #TempTable(sCliNum, dtProc, sAssignNum, sCollectNum, cFees, cAdj1, cAdj2)
SELECT 
    sCliNum, 
    dtProc, 
    sAssignNum, 
    sCollectNum, 
    cFees, 
    cAdj1, 
    cAdj2 
FROM DailyHist

The DailyHist table layout is as follows:

sCliNum dtProc                  sAssignNum  sCollectNum    cFees   cAdj1       cAdj2
----------------------------------------------------------------------------------
BADA    2011-02-01 00:00:00.000 ADJ         (Adj)          0.00    350402.30   0.00
BADA    2011-02-01 00:00:00.000 INTERE      (Adj)          0.00        43.77   0.00

Here is what I'm trying to achieve

sCliNum dtProc  sAssignNum  sCollectNum cFees   cAdj1   cAdj2   year    month
------------------------------------------------------------------------------------
COUN    2013-07-01 00:00:00.000     IntHis  0.00    0.00    0.00    NULL    NULL    NULL     
COUN    2013-07-01 00:00:00.000 C1  FeeHis  0.00    0.00    0.00    NULL    NULL    NULL    

Please help!

Thanks!

Was it helpful?

Solution

Based on what you said, this is what I think you're trying to achieve.

INSERT INTO #TempTable(sCliNum, dtProc, sAssignNum, sCollectNum, cFees, cAdj1, cAdj2, year, month, day)
SELECT 
    sCliNum, 
    dtProc, 
    sAssignNum, 
    sCollectNum, 
    cFees, 
    cAdj1, 
    cAdj2,
    DATEPART(yyyy, dtProc), -- year
    DATEPART(mm, dtProc),   -- month
    DATEPART(dd, dtProc)    -- day
FROM DailyHist
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top