[英]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
. 我有一个表
test
其中包含以下列: id
, startDate
, stopDate
, startOvertime
, stopOvertime
。
startDate
and stopDate
are of type datetime and startOvertime
, stopOvertime
are of type time(7)
. startDate
和stopDate
的类型为datetime和startOvertime
, stopOvertime
的类型为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
. 我想创建之日起,部分新列
stopDate
和时间部分startOvertime
并复制到一个新创建的列test-fill
。
If I use formula (stopDate, startOvertime) then the value of the new datetime column is not right. 如果我使用公式(stopDate,startOvertime),则新的datetime列的值不正确。 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.