SQL Column AutoFill

William Batte 21 Reputation points
2021-05-21T15:02:26.957+00:00

I have a sql table called tktproc with the following column proc_date with data type of datetime.
How can i autofill column acct_period from proc_date in the following format YYYYMM?

Developer technologies Transact-SQL
SQL Server Other
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.5K Reputation points
    2021-05-21T18:00:29.123+00:00

    In case of ancient servers, check the next statement:

    _alter table tktproc add acct_period as (cast(YEAR(proc_date) * 100 + MONTH(proc_date) as varchar(max)))_

    Show the error messages.

    0 comments No comments

4 additional answers

Sort by: Most helpful
  1. Viorel 122.5K Reputation points
    2021-05-21T15:17:45.007+00:00

    Try executing this statement:

    alter table tktproc add acct_period as (FORMAT(proc_date, 'yyyyMM'))

    0 comments No comments

  2. William Batte 21 Reputation points
    2021-05-21T17:35:11.887+00:00

    I'm having trouble getting this to run on SQL 2008R2

    0 comments No comments

  3. William Batte 21 Reputation points
    2021-05-21T18:15:54.85+00:00

    That worked, thanks. Going forward how do I change the query to update new records.


  4. EchoLiu-MSFT 14,621 Reputation points
    2021-05-24T03:16:37.437+00:00

    Hi @William Batte ,

    Welcome to the microsoft TSQL Q&A forum!

    The FORMAT function has been provided since the 2012 version, so it does not work in sql server 2008 R2. In earlier versions, use this:

    ALTER TABLE tktproc ADD acct_period as (REPLACE(LEFT(proc_date,CHARINDEX('-',proc_date)+2),'-',''))  
    

    If you have any question, please feel free to let me know.
    If the response is helpful, please click "Accept Answer" and upvote it.

    Regards
    Echo


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.