简体   繁体   中英

T-SQL Add new column in existing table and fill with value from two another existing column

I have a table test with the following columns: id , startDate , stopDate , startOvertime , stopOvertime .

startDate and stopDate are of type datetime and startOvertime , stopOvertime are of type time(7) .

I want to create a new column with the date portion from stopDate and the time portion from startOvertime and copy that into a newly created column test-fill .

If I use formula (stopDate, startOvertime) then the value of the new datetime column is not right. Any proposals?

If you always want the new column with this information, then you can use a computed column:

alter table test add test-fill as
    (cast(cast(startDate as date) as datetime) + cast(overtime as datetime));

This doesn't actually add a new column. It just computes the values when you need them.

This should do it:

alter table [table-name] add [test-fill] datetime

update [table-name]
set [test-fill] = cast(startDate as date) + cast(stopOvertime as datetime)

First we add column to the table, then we update created cells with data.

ALTER TABLE TEST ADD NEWCOL DATETIME;
UPDATE TEST
SET NEWCOL = CAST((CAST(CAST(stopDate as date) as varchar(10))+' '+CAST(CAST(startOvertime as time) as varchar(10))) as DATETIME);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM