Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sql

sql-server

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?

like image 957
Alex Avatar asked Sep 16 '15 11:09

Alex


People also ask

How do you create a new column in SQL based on another column?

In Microsoft SQL Server, we can change the order of the columns and can add a new column by using ALTER command. ALTER TABLE is used to add, delete/drop or modify columns in the existing table. It is also used to add and drop various constraints on the existing table.

How do you add values after add a new column in the existing table?

this: ALTER TABLE YourTable ADD YourNewColumn INT NOT NULL DEFAULT 10 WITH VALUES; Add the column with null values first. Then update all rows to enter the values you want.

How do you add a column to a table from another table in SQL?

INSERT INTO SELECT Syntax Copy only some columns from one table into another table: INSERT INTO table2 (column1, column2, column3, ...)


1 Answers

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.

like image 196
Gordon Linoff Avatar answered Oct 03 '22 15:10

Gordon Linoff