Skip to content
Advertisement

Adding a SQL column while also filling it in with a value from each row

I have a table with a column LastUpdated of type DateTime, and would like to add a column LastUpdated2 to this table. I would like to populate it with whatever LastUpdated is for each existing row in the table.

Eg:

LastUpdated
12:01 PM
5:00 PM

Becomes:

LastUpdated LastUpdated2
12:01 PM 12:01 PM
5:00 PM 5:00 PM

Quite simply as you can see, I just want them to match.

I see a lot of example out there for an ALTER statement that has a default value, but didn’t find any that have a specific value for each row as they’re updated.

Optimally I’d want my code to be something like this, hopefully this pseudocode makes sense:

I’ve also considered maybe just doing an ALTER statement, and then an UPDATE statement. Maybe this is the only way how to do it?

Advertisement

Answer

I’m thinking there is no way to do this all within the ALTER statement by itself. Needs to be two separate statements:

This accomplishes what I am trying to do I think. I was curious if there was a way to do it inside of just the ALTER statement, but maybe not. I don’t see any examples online.

Advertisement