how to alter a column to load the datepart from another datetime column

Polachan Paily 226 Reputation points
2021-01-12T19:15:48.293+00:00

I have a table

Create table Attendance(id int, ClockedDate datetime, LogDate datetime)
values
(1, 2019-02-25 08:52:15.000, null),
(2, 2019-02-25 08:57:51.000, null)

I want to alter the column LogDate to store date part only from ClockedDate column in the table Attendance

Please help how to alter the existing column to get the date from another column virtually.

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

Accepted answer
  1. Viorel 122.6K Reputation points
    2021-01-12T19:29:21.157+00:00

    Try the next script:

    alter table Attendance drop column LogDate
    alter table Attendance add LogDate as cast(ClockedDate as date)
    

    Check if it worked using select * from Attendance.

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. EchoLiu-MSFT 14,621 Reputation points
    2021-01-13T02:26:13.853+00:00

    Hi @Polachan Paily ,

    Do you consider using the update statement?

    alter table Attendance alter column LogDate date  null;  
    update Attendance  
    set LogDate=cast(ClockedDate as date)  
    from Attendance  
      
    select * from Attendance  
    

    Output:

        id ClockedDate LogDate   
        1 2019-02-25 08:52:15.000 2019-02-25  
        2 2019-02-25 08:57:51.000 2019-02-25  
    

    If you have any question, please feel free to let me know.

    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.

    0 comments No comments

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.